How to wrap each collection object in Java?

I have a class Foofor which I made an equivalence wrapper class WrappedFooto change its contract equals()in some parts of the program.

I need to convert from objects Footo objects WrappedFooand vice versa in many places. But I also need to convert Collectionfrom Fooand WrappedFoofrom one to another. Is there a way that I can achieve this in a general way?

Basically, I want to use a method like this:

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

The problem is that I don’t know which implementation Collectionwill be used, and I want to keep the same implementation for the resulting one Collection.

+4
source share
3 answers

Using the Reflection API, you can do something like this (note the 0name of the method):

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 we implement the overloading methods of a whole series with one layer, using the method described above (note 0in 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);
}

...
+2
source

The Collection interface guarantees the existence of a "boolean addAll (Collection c)" method. I would try something along these lines:

public static Collection<WrappedFoo> wrapFoos(Collection<Foo> col) {
  Class<?> colClass = col.getClass();
  Collection<WappedFoo> newCol = colClass.getConstructor().getInstance();
  newCol.addAll(col);
  return newCol;
}
+2
source

, Collections2.transform Google Guava , .

, Foo WrappedFoo. , (, ​​ , ).

+1
source

Source: https://habr.com/ru/post/1525520/


All Articles