Note: I made a mistake in my answer…
This is the correct way to make a list:
List<String> reversedList = new ArrayList<>()
The mistake that I wrote is a bad way to make a list, but it actually works:
List reversedList = new ArrayList()
Why does it work? I think it’s the same as writing:
List<Object> reversedList = new ArrayList<>()
We essentially created a list that can contain any Object, a.k.a anything. This might seem convenient, but it’s a bad habbit. Let’s add two different type of objects to our list:
Double someNumber = 5.0;
Double someOtherNumber = 2.0;
String someText = “hello”;
Note that we added a String and two Doubles to our list. The code is still working, so this might not always cause issues, but imagine you created your list to contain some numbers that you want to do calculations with. Let’s say we want to add all numbers together.
When you add 5.0 and 2.0 together it becomes 7.0. When you add 7.0 and “hello” together it becomes “7.0hello”. This can mean that your code will run, but if you give the wrong input it will crash.
With that cleared out, I just want to clear up some possible misconceptions:
It is possible to do: List<String> myList1 = new ArrayList<String>() or List<String> myList2 = new ArrayList<>(). These two mean the same thing.
It is not possible to do List<String> impossibleList = ArrayList<Double>(). This is similar to: String exampleVariable = 1.0. You can’t declare a variable and then give it a value that it cannot contain.
I think the first two points explains your original question.
It is impossible to do List<String> impossibleList = List<>(). Why? If you look in the List documentation you see that List is an interface – not a class. If you’re not familiar with interfaces, think of it like requirements of what methods should exist. However, the interface is just an empty shell and the required methods are not implemented.
So why is it possible to do the following?
List<String> someKindOfList = new ArrayList<>();
Since there are two things happening here, let’s make them clear:
someKindOfList = new ArrayList<>();
On the first line, we create a variable and decide that it should be some kind of List.
On the second line, we give the variable a value. In this case we want an ArrayList, but it’s not our only choice. You can see a list of all classes in the List documentation.
- So why does the following not work?
If you look in the HashMap documentation, you see that the HashMap class does not implement the List interface (at the top, “all implemented interfaces”).
When you declare a variable you can be broad and say it’s going to be “some type of list” (interface).
When you initialize a variable (give it a value), you have to provide a “specific type of list” (class).