2

What is the difference between this two line:

ArrayList<Integer> iList = new ArrayList<Integer>();
ArrayList iList = new ArrayList<Integer>();   

Step 1: raise a compile time error

public static void main(String args[]){
    ArrayList<Integer> iList = new ArrayList<Integer>();
    iList.add(10);
    iList.add("Test_Element"); // Compiler error, while trying to insert a String in an Integer ArrayList 
    System.out.print("Value of 2nd element: " + iList.get(1));
 }

Step 2: works fine

public static void main(String args[]){
    ArrayList iList = new ArrayList<Integer>();
    iList.add(10);
    iList.add("Test_Element"); // works fine, while trying to insert a String in an Integer ArrayList 
    System.out.print("Value of 2nd element: " + iList.get(1));
 } 

Output: Value of 2nd element: Test_Element

I am expecting an error like

"add(java.lang.Integer) in ArrayList cannot be applied to (java.lang.String)", but in step2 two it works fine.

Could anyone please explain me, why I am able to insert a String in this list.

SKG
  • 39
  • 2

1 Answers1

0

There's no compile-time check on generic type of ArrayList when you write ArrayList list = new ArrayList<Integer>(). The generic type on the right side of the assignment expression is basically ignored. ArrayList doesn't really have an inner type, just that the T in ArrayList<T> helps you make sure you only perform operations with instances of T on your list.

It would be useful to understand why you want to have integers and strings mixed in the same ArrayList--there might be a design smell here :)

johnheroy
  • 416
  • 2
  • 7