开发者

PArsing from Set<TypeA> to Set<TypeB>

开发者 https://www.devze.com 2023-01-27 05:41 出处:网络
I have a curious question, I hope someone can help me. I am using Java. I receive a Set from a method. This TypeA is exactly what I want, but I would like to add some more functionalities to it, in o

I have a curious question, I hope someone can help me. I am using Java.

I receive a Set from a method. This TypeA is exactly what I want, but I would like to add some more functionalities to it, in order to increase code cleanness.

In C# I could write Extension Methods, but I don't think Java has something like that, so I would like to create a new type, TypeB, that contains开发者_StackOverflow a TypeA variable and performs the extra function that I want (something like an Wrapper/Adapter). but the problem is:

I can't do

Set<TypeB> mySet = myMethod();

or

Set<TypeB> mySet = (Set<TypeB>)myMethod();

What would be perfect would be something like that

Set<TypeB> mySet = new Set<TypeB>(myMethod());

But Set is a Java type, so I can't add a constructor to it.

How could I do so I can parse it in a clean way? If I add a method like

Set<TypeB> mySet = parse(myMethod());

I would have to iterate through all items in myMethod, which would not be very performatic.

Is there any better solution than creating this method?

Thanks, Oscar


What if you added functionality not by inheriting from TypeA, but by using functions (static methods):

So instead of:

public class TypeB {
    TypeA self;
    public void Frobnicate(int foo) {...}
}

Write:

public class TypeAUtils {
    public static void Frobnicate(TypeA self, int foo) {...}
}

C# extension methods are just syntactic sugar for this technique anyway.

This is one of my favorite design patterns. I call it "functions", and it is highly underrated. :-P

If you can't do it this way (and thus you wouldn't be able to with extension methods either), then you must be adding state to TypeA, in which case you have to allocate more memory for each object in your set, which means you can't avoid iterating.


Only smt like this

Set<TypeB> parse(Set<TypeA> old){
   Set<TypeB> res = new HashSet<TypeB>();
   for(TypeA a : old) res.add(new TypeB(a));
   return res;
}

Or create your own Set.


EDIT

(Revised, based on the OP's clarifiying comment below.)

Let us assume that B has a constructor

    public B(A a) { ... }

which creates a B adapting an A instance. Then the simplest way to create a Set<B> from a Set<A> is:

    Set<A> aset = ...
    Set<B> bset = new HashSet<B>(aset.size());
    for (A a : aset) {
        bset.add(new B(a));
    }

The Apache Commons Collections and Guava Collections include infrastructure that can transform a collection of one class to a collection of another, but they would be overkill for something as simple as this. (But if you did want to go down that route, Guava would be better because the APIs are generics-aware.)

0

精彩评论

暂无评论...
验证码 换一张
取 消