newInstance, generics, and "unchecked or unsafe operations"
Hi Everyone,
I'm trying to create a method in a class that takes some type of
genericized collection and creates a new, empty instance of it by
calling the newInstance method. I can get the code to work, but I do
get compiler warnings of "unchecked or unsafe operations".
Please note, I would like this code to be flexible, so whether the
method gets an ArrayList<Integer> or a LinkedList<String> it will work
and not generate compiler warnings.
In trying to hunt down a solution by reading comp.lang.java.programmer
and other online sources, I became aware of the issue of "type
erasure". In fact, at compile time I should know the full type of the
collection. Is there a way to "nicely" re-write this code, so it
doesn't generate the warning? If not "nicely" how about "nastily"?
====
import java.util.Collection;
import java.util.ArrayList;
class EmptyDuplicator<T>
{
public Collection<T> duplicateEmptyVersionOf(Collection<T>
original)
throws InstantiationException, IllegalAccessException
{
// COMPILER WARNING on next line; BUT I KNOW T at compile-
time!!!
Collection<T> emptyVersionOf =
original.getClass().newInstance();
return emptyVersionOf;
}
}
public class Sample
{
public static void main(String[] args)
throws InstantiationException, IllegalAccessException
{
ArrayList<Integer> original = new ArrayList<Integer>();
original.add(1);
original.add(2);
EmptyDuplicator<Integer> duplicator = new
EmptyDuplicator<Integer>();
Collection<Integer> clone =
duplicator.duplicateEmptyVersionOf(original);
clone.add(4);
System.out.println("original");
for(int i : original) {
System.out.println(i);
}
System.out.println("clone");
for(int i : clone) {
System.out.println(i);
}
}
}
====
Thanks in advance,
Eric