Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the convention for instantiating collections of user defined types?

I have a class called MatchingLine

    public class MatchingLine implements Comparable
     {
        private String matchingLine;
        private int numberOfMatches;

        // constructor...
        // getters and setters...
        // interface method implementation...
     }

I am using this class in an ArrayList as follows -

    ArrayList<MatchingLine> matchingLines = new ArrayList<MatchingLine>();

However, the Netbeans IDE puts a note beside this statement and says,

   redundant type arguments in new expression (use diamond operator instead)

and it suggests that I use -

    ArrayList<MatchingLine> matchingLines = new ArrayList<>();

I always thought the former style was the convention? Is the latter style the convention?

like image 659
CodeBlue Avatar asked Apr 09 '12 15:04

CodeBlue


2 Answers

ArrayList<MatchingLine> matchingLines = new ArrayList<>();

This is a new feature in Java 7 called diamond operator.

like image 109
Eng.Fouad Avatar answered Sep 18 '22 14:09

Eng.Fouad


As Eng mentioned, this is a new feature of Java 7.

It compiles no differently than the fully declared statement with all the type parameters specified. It is just one way that Java is trying to cut down on all the redundant type information you must enter.

In a statement such as (just for illustration; Callback is best known as an interface):

Callback<ListCell<Client>,ListView<Client>> cb = new 
    Callback<ListCell<Client>,ListView<Client>>();

It is quite obvious to the reader what the types are in this very wordy declaration. In fact the type declarations are excessive and make the code less readable. So now the compiler is able to simply use type inference in conjunction with the diamond operator, allowing you to simply use:

Callback<ListCell<Client>,ListView<Client>> cb = new Callback<>();
like image 29
scottb Avatar answered Sep 21 '22 14:09

scottb