0

I'm trying to understand the java compiler generics types erasure with the following exemple. Can someone explain me why can i add a new motor bike into a list of Car ?

List<Vehicle> list = (List<Vehicle>)(Object)new ArrayList<Car>(); 
list.add(new MotorBike());
shmosel
  • 42,915
  • 5
  • 56
  • 120
  • 2
    Firstly we dont know your class structure. Secondly: *"can"* referring to runtime or compile time - have you tried retrieving the object back from the list? – luk2302 Mar 06 '18 at 22:01
  • The answer is in the question: type erasure. Google that term, and you'll have plenty of answers. – JB Nizet Mar 06 '18 at 22:01
  • @luk2302 You can always do `((List)list).get(0)`. – shmosel Mar 06 '18 at 22:11
  • @luk2302 i had not describe my class structure because it is obvious. Car and MotorBike inherit from vehicle. Yes i've tried this ! it works. I understand why comilation succeed i just don't know why runtime accept my add – olivier schirm Mar 06 '18 at 22:22
  • Because Runtime does not have generics and List contains Objects – luk2302 Mar 07 '18 at 06:13

0 Answers0