Mixing generic and non-generic collections in java
I am faced with a dilemma in mixing general and non-general collection. For example: This is new java 5/6 generic code.
List<Integer> list = new ArrayList<Integer>();
list.add(5);
Alpha a = new Alpha();
a.insert(list);
for (Integer integer : list) {
System.out.println(integer); //will get classCastException
}
Non-generic legacy code
public class Alpha {
public void insert(List list) {
list.add(new String("50"));
}
}
I know that at runtime I am getting a classCastException at runtime. But I want to print all the list items even after adding Strings / Dogs. Can someone please tell me how I can achieve this?
source to share
Of course - you just need to avoid the compiler inserting the cast for you:
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
// Nice strongly-typed list...
List<Integer> list = new ArrayList<Integer>();
list.add(5);
// Now abuse it...
List raw = list;
raw.add("Bad element");
// Don't use the "integer" part, effectively...
for (Object x : list) {
System.out.println(x);
}
}
}
Now the compiler doesn't translate every element into Integer
, so we're fine.
However - if you have to do this, it means that your code is a bit broken at the root. You will be much better off committing Alpha
to avoid adding unexpected items to the list.
source to share