I’m a bit of a Java N00B, but I am majorly confused about clone.
Consider the following incorrect class
class blah {
public blah(Collection<Integer> c){
member_collection = c.clone(); //the clone here is defensive
}
private final Collection<Integer> member_collection;
}
I think what I want to do is clear.
I understand why the clone() symbol is not found: clone is not a public method in any possibly Collection. However, in any concrete class I would want to use it is, and I want to just tell the compiler that.
I’m sure I’m not the first person to want to clone a generic collection, but the tutorials I have looked at only explain why you cannot clone a Collection, not how to get around the problem. I have tried hacky stuff with getClass() and casting, but those usually require me to make ugly try-catch blocks and it’s difficult to ensure exactly one initialization (the pointer member_collection) is final!
What I’d really like to do is somehow put that information into the type somehow. Is there a nice way to do this?
Thanks!
You’re better off copying like so:
Or like so:
This is the same as what you’re trying and guarantees that any order of the given
Collectionis preserved.Edit: If you absolutely need it to be the same implementation as the one given to you and you don’t want to rethink your design, then you can do some of the hacky reflection stuff and put it in a
staticmethod.Must of the concrete collections implement
cloneas a public method, so this should work for most of them. It will benullfor the ones that don’t. You may want to just rethrow whatever exception you get instead.