0
ArrayList list1 = new ArrayList (); 
list1.add(1);
list1.add(2); 
list1.add("Aman"); 
list1.add("Shukla"); 

ArrayList<String> list2 = new ArrayList<String>(list1); 
list2.add("practicing"); 
list2.add("Java");
System.out.println("ArrayList is " + list2);

I'm expecting an error because the values that i'd entered in ArrayList list1 are Integer type and then these got copied into the ArrayList list2 of type String successfully.

Then how come is concept of Generics offering type safety?

  • 1
    You lost the type safety when you used a raw-typed list. Don't use raw types; pay close attention to the compiler warnings. – Andy Turner Jan 28 '20 at 18:25
  • @AndyTurner the concept of generics was derived for providing Type safety to raw type. Hope you Understand my concern. List2 in here must insure to only store string type data – Aman Shukla Jan 28 '20 at 18:45
  • 1
    The compiler warned you that your code is unsafe. You chose to ignore the warning. – VGR Jan 28 '20 at 19:31

0 Answers0