From charlesreid1

The "diamond notation" in Javascript refers to the use of angular brackets to denote generic types, on BOTH the left and right side for assignment.

Generic types

Referring to generic types in general, we might define an object like "Container" that stores one object. If we don't use any generic types, we can accomplish this by having our Container object store a reference to the most generic type of object we can find - the Object type, the parent class of every object.

public class Container {
    private Object object;
    public void set(Object object) { this.object = object; }
    public Object get() { return object; }

Why is this bad? It's bad because "Object" gives us ''too much'' freedom and flexibility. Now, potentially the user can pass in any type they want. The problem, then is '''at compile time there is no way to know what is going to happen or how the object is going to be used.'''

Catching problems at compile time, rather than run time, is always preferred, so the problem with this way of doing things is that it shunts these problems until runtime. 

Instead, we can specify that the container's object should be a generic, but specific, type:

public class Container<T> {
    private T object;
    public void set(T object) { this.object = T; }
    public T get() { return object; }

See this Oracle Java tutorial for more info.

Diamond notation

For example, the following list declaration uses the diamond syntax (and shorthand on the right hand side):

List<String> list = new LinkedList<>();

Contrast this with older versions of Java (5-6) where you would do the above like this:

List<String> list = new LinkedList();

The diamond notation is important for collections because collections wrap generic types. The diamond notation is also important because it keeps two objects of the same type (two List objects) that wrap different kinds of data from being mixed together.

For example, suppose you have a list of strings:

List<String> strings = ...

Now you want to create a list of integers. So you do this:

List<Integer> integers = new LinkedList(strings);

Strictly speaking, this is legal - without the diamond notation, the variable strings is the same type as the variable integers, and Java ignores what types they store under the hood.

With diamond notation, two objects of the same type that wrap different generic types will not be combined, and the above code will throw a compiler error.


See also: