I'm currently studying for the Java OCA exam and came across a question relating to ArrayList declarations.
Which of the following is valid?:
1. ArrayList al1 = new ArrayList(); 2. ArrayList al2 = new ArrayList<>(); 3. ArrayList<> al3 = new ArrayList<>(); 4. ArrayList<Double> al4 = new ArrayList<>(); 5. ArrayList<Double> al5 = new ArrayList<Float>();
According to my book, answers 1,2 and 4 are valid. Answers 3 and 5 are invalid.
However, no proper explanation is given. All it does is show the standard way to declare an ArrayList:
ArrayList<E> al3 = new ArrayList<E>();
and mentions that it's also valid to declare the ArrayList without the generic part.
I'm also unable to find a decent article on this topic online. Can someone explain (or point me in the direction of a good article) the different permutations above?
Thanks in advance.
<>is called thediamond operatorand was introduced withjava7. it is a shortcut for instatiating generic objects, so you do not have to specify the type a second time when usingnewsince it is already specified in the variable declaration.ArrayList<Type> l = new ArrayList<>()is just a short form ofArrayList<Type> l = new ArrayList<Type>(). This is the ONLY valid case where blank angles occur. Blank angles are invalid in previous java versions, and the types should be consistent (Double and Float are NOT). You should look at the old syntax, which is more clear.