Erick Robertson
Erick Robertson

Reputation: 33082

Why aren't generic types required when calling a constructor?

I understand about type erasure surrounding generics, but I was still surprised to find that this code generates no error:

public class MyClass {
  private final HashMap<ClassA,ClassB> hashMap;

  public MyClass() {
    this.hashMap = new HashMap<>();
  }
}

Mostly, I use the Java Standard version of Eclipse with Java 1.6, and the generic types are auto-filled when I select the auto-completed constructor name. I'm now using the J2EE version of Eclipse and Java 1.7, and they're not. The code compiles and it's fine. It's completely redundant information, so I don't see why it should be required. But it just feels wrong that you don't have to put it.

Why is this not required, or am I totally missing something here?

Upvotes: 0

Views: 84

Answers (1)

Petr Janeček
Petr Janeček

Reputation: 38444

Actually, by typing <>, you say "Hey, compiler, do the work for me and fill the generics in as they are stated in the declaration."

It's called diamond operator and is new to Java 7, see e.g. this question on SO or the official tutorial.

If you wrote this.hashMap = new HashMap(); instead, then the compiler should complain (and generally throw a warning).

Upvotes: 4

Related Questions