Scenario: A method addList
in class expects a List
of Integer
objects.
main
method sends an ArrayList
argument containing objects of multiple types, not just Integer
.
Result: Call to method addList
is successful and it is also possible to retrieve the objects stored in the ArrayList
and print them.
Question: Should not we expect that on run-time when the list is received in the called method, its content will be validated and it will result in some exception?
However, in addList
method, if I am trying to insert a non-Integer
object in the ArrayList
, it fails at compile time only.
Does this conclude that Diamond operator constraint is only while inserting the objects in a Collection?
Please note, erasure-in-generics is different question and doesn't provide answer to this question.
package com.rnd.nirav;
import java.util.ArrayList;
import java.util.List;
public class OverRidingTest {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add(Integer.valueOf(1));
list.add("Nirav");
list.add(Float.valueOf(1.1f));
addList(list);
}
public static void addList(List<Integer> list) {
list.add("Khandhedia"); // This fails as expected.
System.out.println("List size = " + list.size());
Iterator itr = list.iterator();
while(itr.hasNext())
{
System.out.println("Element is " + itr.next());
}
}
}