Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the compiler allow me to assign a generic collection to a variable declared as a class-specific collection?

Tags:

java

generics

I'm having trouble understanding why the java-compiler allows non-specific collections to be assigned collections where the variable have been specified. Like this:

    ArrayList list = new ArrayList();
    // Operations on list
    ArrayList<String> stringList = list;

There's potential for all kinds of casting errors in this, it seems to me it would make more sense if the compiler stopped you from doing this in the first place.

I'm only asking because I'm curious of this somewhat weird aspect of the language, I don't actually have trouble getting the code to work (although I might some day when I need to use an ArrayList with all kinds of classes in it).

like image 355
GarlandGreen Avatar asked Feb 18 '23 22:02

GarlandGreen


1 Answers

Its just for supporting legacy code before generics or java 5.

Generics, introduced in Java SE 5 and Collection has been running since long back. So if you see Collection framework before 1.5 you see ArrayList, there is no generic.

like image 190
Subhrajyoti Majumder Avatar answered Feb 27 '23 14:02

Subhrajyoti Majumder