0

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?

Erick Robertson
  • 32,125
  • 13
  • 69
  • 98
  • 1
    [Enhanced diamond notation](http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html) is a new feature in Java 7. – Perception May 18 '12 at 01:07

1 Answers1

4

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).

Community
  • 1
  • 1
Petr Janeček
  • 37,768
  • 12
  • 121
  • 145
  • From reading the other SO question, it seems the whole point is to trigger the compile-time generic type-checking of constructor arguments. We know what the types are, so we don't have to specify them, but it lets the compiler know there are types which need to be checked. – Erick Robertson May 18 '12 at 01:19
  • Yep. We know the types, but are too lazy to write the generic types twice in one line. Diamond's only purpose, as far as I know, is to save us the time (and legibility!) we would spend typing the same thing again and again and again, when we can just write "that thing goes here again". – Petr Janeček May 18 '12 at 01:25