How to wrap each object of a Collection in Java? -
i have class foo
made equivalence wrapper class wrappedfoo
change equals()
contract in parts of program.
i need convert foo
objects wrappedfoo
objects , vice versa in many places. need convert collection
s of foo
s , wrappedfoo
1 another. there way can achieve in generic way?
basically want method this:
public static collection<wrappedfoo> wrapcollection(collection<foo> collection)
the problem don't know kind of collection
implementation used , wish keep same implementation resulting collection
.
using reflection api, (notice 0
in method name):
public static collection<wrapperfoo> wrapcollection0(collection<foo> src) { try { class<? extends collection> clazz = src.getclass(); collection dst = clazz.newinstance(); (foo foo : src) { dst.add(new wrapperfoo(foo)); } return dst; } catch(exception e) { e.printstacktrace(); return null; } }
now implement whole bunch one-liner overload methods using method above (notice 0
in 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); } ...
Comments
Post a Comment