Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Diamond operator in raw type context

Tags:

java

generics

I saw code like this today:

public class GenClass<T> { ... }

//in some other class
GenClass g = new GenClass<>();

Does the <> accomplish anything at all here? Normally <> would tell the compiler to determine the generic parameter(s) based on context, but in this case there's no context. But apparently it's legal. Is there any difference between this and the following?

GenClass g = new GenClass();
like image 726
ajb Avatar asked Apr 01 '16 18:04

ajb


People also ask

What is the purpose of diamond operator in Java?

Diamond Operator: Diamond operator was introduced in Java 7 as a new feature. The main purpose of the diamond operator is to simplify the use of generics when creating an object. It avoids unchecked warnings in a program and makes the program more readable.

What is Diamond inference in Java?

The diamond operator – introduced in Java 1.7 – adds type inference and reduces the verbosity in the assignments – when using generics: List<String> cars = new ArrayList<>(); The Java 1.7 compiler's type inference feature determines the most suitable constructor declaration that matches the invocation.

Which of the following options is the correct name for empty type parameter rectangle square diamond circle?

It's called diamond operator and infers the generic type from the left hand side, if possible.


1 Answers

The diamond is doing what it always does - inferring the generic type from the context, and providing assurance that the constructor call does not compromise type-safety.

Consider this example:

public class GenClass<T> {

    GenClass(T t, List<T> list) {}

    public static void main(String[] args) {
        GenClass m = new GenClass<>(1, new ArrayList<String>());  // Doesn't compile
    }
}

This example does not compile, because an appropriate type could not be inferred. If you remove the diamond it does compile because the types of the constructor arguments are the erased versions (Object and List).

In your case, the constructor takes no arguments, so there is nothing really to check. However, using a diamond is a good habit to get into, even when you choose to assign the result of a constructor invocation to Object or a raw type (not that you should use raw types).

like image 61
Paul Boddington Avatar answered Oct 16 '22 10:10

Paul Boddington