Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap each object of a Collection in Java?

I have a class Foo for which I made an equivalence wrapper class WrappedFoo to change its equals() contract in some parts of the program.

I need to convert from Foo objects to WrappedFoo objects and vice versa in many places. But I also need to convert Collections of Foos and WrappedFoo from one to another. Is there any way I can achieve this in a generic way?

Basically I want a method that like this:

public static Collection<WrappedFoo> wrapCollection(Collection<Foo> collection)

The problem is that I don't know what kind of Collection implementation will be used and I wish to keep the same implementation for the resulting Collection.

like image 718
qwertzguy Avatar asked Feb 05 '14 23:02

qwertzguy


1 Answers

Using the Reflection API, you could do something like this (notice the 0 in the method name):

public static Collection<WrapperFoo> wrapCollection0(Collection<Foo> src)
{
    try
    {
        Class<? extends Collection> clazz = src.getClass();
        Collection dst = clazz.newInstance();
        for (Foo foo : src)
        {
            dst.add(new WrapperFoo(foo));
        }
        return dst;
    } catch(Exception e)
    {
        e.printStackTrace();
        return null;
    }
}

Now implement a whole bunch one-liner overload methods using the method above (notice the 0 in the calls):

public static ArrayList<WrapperFoo> wrapCollection(ArrayList<Foo> src)
{
    return (ArrayList<WrapperFoo>) wrapCollection0(src);
}

public static Vector<WrapperFoo> wrapCollection(Vector<Foo> src)
{
    return (Vector<WrapperFoo>) wrapCollection0(src);
}

...
like image 116
Martijn Courteaux Avatar answered Oct 29 '22 16:10

Martijn Courteaux