Why does the compiler allow me to assign a common collection to a variable declared as a collection belonging to a class?

I am having trouble understanding why the java compiler allows non-specific collections to assign collections in which a variable is specified. Like this:

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

This has potential for all kinds of casting errors, it seems to me that it makes sense if the compiler stops you from doing this.

I just ask because I'm curious about this strange aspect of the language, I have no problem getting the code to work (although I could someday use an ArrayList with all kinds of classes in it).

+4
source share
2 answers

Only to support legacy code before generics or java 5.

General introduced in Java SE 5 , and the collection has been operating since ancient times. So, if you see Framework Collection up to 1.5, you see ArrayList , no generic .

+6
source

Since using the original types (for example, an ArrayList without a common parameter) leads to warnings if they are not suppressed, you can also use the -Werror flag for β€œfail on warning”:

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

(although I personally have not used this flag yet)

+2
source

Source: https://habr.com/ru/post/1438843/


All Articles