I found a way to add Floats to an Integer array through generic types. I'm curious why Java doesn't catch this in a runtime error? I tried looking through the docs for any info about this, but I haven't had any luck.
For example, say I have two ArrayLists, one containing Integers, and one containing Floats, like so:
ArrayList<Integer> listInt = new ArrayList<>();
ArrayList<Float> listFlt = new ArrayList<>();
listInt.add(6);
listInt.add(71);
listFlt.add(4.92f);
listFlt.add(20.5f);
Using generics, I can copy the Floats from listFlt into listInt through a method like this:
public static <T extends Number, S extends Number> void copy(ArrayList<T> src, ArrayList<S> dest) {
for (int i = 0; i < src.size(); i++) {
Object x = src.get(i);
dest.set(i, (S)x);
}
}
Calling it with:
ClassName.<Float, Integer>copy(listFlt, listInt);
Now, when I print listInt, it displays:
4.92
20.5
How is it possible to cast an Object as an Integer when generics are involved? And how can listInt store Floats? Thanks!