GarlandGreen
GarlandGreen

Reputation: 51

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

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).

Upvotes: 4

Views: 144

Answers (2)

Puce
Puce

Reputation: 38132

Since using raw types (eg ArrayList without generic parameter) results in warnings if not suppressed, you could also consider to use the "-Werror" flag to "fail on warning":

http://docs.oracle.com/javase/7/docs/technotes/tools/windows/javac.html

(though personally, I haven't used this flag yet)

Upvotes: 2

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

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.

Upvotes: 6

Related Questions