1

I read so many articles but I can't understand the difference between these two lines:

ArrayList<String> list = new ArrayList();
ArrayList<String> list = new ArrayList<String>();

The only difference I see that the first line trigger an "Unchecked assignment" warning.

Roman Roman
  • 617
  • 1
  • 9
  • 16
  • 3
    What happens if you do `ArrayList list = new ArrayList(Arrays.asList(1,2,3));` - and if you print the `list`? Try it. – Elliott Frisch Jan 02 '18 at 14:11
  • I know about that, but what about empty constructor call? – Roman Roman Jan 02 '18 at 14:12
  • You're using a raw type, making it impossible for the compiler to check if your code is typesafe, hence the warning. It doesn't matter much here, but it's still wrong, in that it encourages sloppy programming, using raw types (as shown in the example from Elliott). It also adds a compilation warning, that you should avoid in general (at least to be able to easily detect other warnings with a bigger severity). – JB Nizet Jan 02 '18 at 14:15
  • This is pretty straight forward. `new ArrayList()` is creating a raw type array list. Then you are assigning that raw type to a reference that has a type to it. Hence you have made an unsafe/unchecked assignment. – matt Jan 02 '18 at 14:16
  • 4
    FYI, there's a third option `ArrayList list = new ArrayList<>();` which is equivalent to the second one, except [the type is inferred](https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html), meaning you don't need to write `String` twice. – Michael Jan 02 '18 at 14:18

2 Answers2

4

With unchecked assignment you could add objects of incorrect types. What would lead to RuntimeException. E.g. you could add Integers to the list. With types this is not possible.

  ArrayList<String> list = new ArrayList(Arrays.asList(1));
        ArrayList<String> list = new ArrayList<String>(Arrays.asList(1));

First one is accepted and the second one comes up with an compile error.

shalama
  • 1,133
  • 1
  • 11
  • 25
1

You could make a raw list.

List list = new ArrayList();

That is fine, you now have a raw list, that you can put any object into. If you want to assign that list to a typed version, you will make an unchecked assignment.

List<String> strings = list;

That is because, what was put into list was never checked to be a string.

matt
  • 10,892
  • 3
  • 22
  • 34
  • 1
    "That is fine" Contentious. – Michael Jan 02 '18 at 14:23
  • Fine for the compiler, though pretty cumbersome for the programmer. Using raw types doesn't get a warning. – matt Jan 02 '18 at 14:33
  • "Using raw types is still acceptable java" Only if you're interacting with legacy code. Otherwise, they are strongly discouraged. – Andy Turner Jan 02 '18 at 14:35
  • @AndyTurner I edited that to say it doesn't get a warning, because certainly if somebody was to use raw types in any sort of project not targeting java 1.4, it wouldn't be "acceptable." – matt Jan 02 '18 at 14:39