Hi ranchers,
ArrayList<String> list3 = new ArrayList();
ArrayList<String> list4 = new ArrayList<String>();
I don't want to talk about the second line of code, because it is perfect.
But the first line:
ArrayList<String> list3 = new ArrayList(); You can write code like this, it compiles (with a warning) and runs perfectly.
Since the type of list3 is ArrayList<String> you can add Strings to and retrieve Strings (and only Strings) from it.
Trying to add something else (e.g. an Integer or an Object) will result in compile time error. So we are on the safe side, there will no clast cast exceptions at runtime, because adding wrong things would simply not compile.
So why the warning?
The situation of the line occurs in reassigning variable list3. The line (as it is) is a bit unnatural, because nobody would write such a code. But a similar situation arises when you use old code without generics ("legacy code"). Imagine a method that returns you an ArrayList. Not an ArrayList<String>, just a raw type ArrayList. And you type:
ArrayList<String> list5;
list5 = theMethodThatReturnsMeAnArrayList(); In this case the compiler cannot check for type safety. It cannot know if the list is ok, because what the method returns is a raw type ArrayList. So the compiler warns you:"Hey, Chris, the method returns a list that may contain something else than Strings. Please go into the API of that method and assert, that the list the method returns contains only Strings, nothing else!".
Small simulation:
if you paste this code in a main method of a
test class of your choice and compile it with
javac -Xlint:unchecked YourFile.java you'll get a warning about type safety in the indicated line. You also get warnings in the lines where you add something to the legacyList (but I was assuming, this is from old code, somebody has already compile in
Java 1.4 or lower).
But it compiles. It compiles and you are warned, that it is not type safe.
You can run it, it will produce a class cast exception in the second for-loop.
But you were warned. If the old code didn't add an Integer to the list, there would have been no exception at runtime.
That's the difference between your lines.
Yours,
Bu.