W
W
WildCherryCandy2015-01-14 19:01:18
Java
WildCherryCandy, 2015-01-14 19:01:18

What is the difference between new ArrayList() and new ArrayList()?

Hello.
Actually, what is the difference between and ? PS In the subject of the question, < > is not displayed. List<T> list = new ArrayList<>();
List<T> list = new ArrayList();

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuri Kan, 2015-01-14
@WildCherryCandy

The form of notation with angle brackets indicates that we used a generic class (generic or generalization) with typed parameters.
Java 7 introduced a shortened notation called diamond. You can omit the parameter on the right side of the expression.
ArrayList catnamesList = new ArrayList<>();
It's worth it just to google it ;)

T
Tagir Valeev, 2015-01-16
@tagir_valeev

In this particular case, in Java 1.7 and older, you won't get any visible difference other than the presence or absence of two compile-time warnings. But, of course, angle brackets are better written. The absence of angle brackets means "first I construct an object that is not parameterized at all, and then I assign it to a variable using unsafe type casting", and the presence of them means "choose the appropriate parameters for the object based on the context." The difference can manifest itself, for example, in the following code:

class NumberList<T extends Number> extends ArrayList<T> { ... }

public static void main(String... args) {
    List<String> list = new NumberList();
    ...
}

This code compiles (with warnings), but you might have weird problems at runtime. If you put two angle brackets, then there will be a compilation error: the appropriate type cannot be deduced.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question