14

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?

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
CodeBlue
  • 14,631
  • 33
  • 94
  • 132
  • 1
    Btw, developers are encouraged to use as abstract types of variables as possible. So ``Collection> var`` or ``List> var`` are preferred. – Alexey Berezkin Apr 09 '12 at 15:28
  • @Alexey: preferred in certain situations. Depending on what you're doing, though, List> can be impossible to work with. It is impossible to add and new objects at all to a List> (aside from null). – scottb Jun 01 '13 at 15:33

2 Answers2

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

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

Community
  • 1
  • 1
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
1

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<>();
scottb
  • 9,908
  • 3
  • 40
  • 56