Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the diamond operator <> equivalent to <?>

Tags:

java

generics

I found in the util.TreeSet class that one of the constructor is calling another constructor with a new TreeMap with empty generic type.

  public TreeSet(Comparator<? super E> comparator) {
         this(new TreeMap<>(comparator));
  }

What does new TreeMap<> mean ? is that equivalent to new TreeMap<?> ?

like image 306
peter Avatar asked Aug 10 '12 14:08

peter


People also ask

Which Java version is diamond operator?

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.

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.

What is the generic in Java?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.

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

This is Java 7 syntax. The diamond (<>) is a short-hand to ask the Java compiler to fill generic arguments with whatever makes sense in the local context (in this case, it'll be ? super E).

like image 110
Romain Avatar answered Oct 13 '22 19:10

Romain