Why is it possible to insert a String
into a List<Integer>
in the following code? I have a class which inserts numbers into a List of Integers:
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(3);
list.add(4);
Inserter inserter = new Inserter();
inserter.insertValue(list);
System.out.print(list);
}
}
Then I have a separate class which inserts a String
into a List
, with the numeric string value "42"
:
public class Inserter {
void insertValue(List list)
{
list.add(new String("42"));
}
}
Why does the compiler not raise a compiler error, or the runtime throw a runtime exception such as *CastException
, when I add the String
to the List of Integer? Also, why does System.out.print(list)
produce output like the following without throwing any exceptions?
[2, 3, 4, 42]
What is the fundamental reason that allows all this to happen?