Generics and clone().
I am trying to do
ArrayList<Integer> tempList = (ArrayList <Integer>) list.clone();
but I get the unchecked warning. list is defined as ArrayList<Integer> list
.
Basically, I am trying to cast the clone of list so that list remains unchanged by my method, so I am creating a templist using the clone. I am confused with respect to how to go about doing this cast using generics.
Thanks in advance.
[453 byte] By [
tkera] at [2007-10-2 5:47:45]

My guess is that your code does not say what you think it says, considering the following does not trigger any warnings.
public class Test {
public static void main(String[] arguments) {
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> clone = (ArrayList<Integer>)list;
}
}
I personally avoid clone() like the plague anyway. Why not do something like this?
ArrayList<Integer> clone = new ArrayList<Integer>();
clone.addAll(list);
Drake
This version gives the warning:
public class Test {
public static void main(String[] arguments) {
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> clone = (ArrayList<Integer>)list.clone();
}
}
However, Drake_Dun is right, you probably want to copy the
list rather than cloning it. If you insist on using clone without a
warning, you loose the type information:
public class Test {
public static void main(String[] arguments) {
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<?> clone = (ArrayList<?>)list.clone();
}
}