What is the default behavior of the diamond operator

1.1k Views Asked by At

I remember seeing a declaration something like the following:

private static Logger log = Logger.getLogger(<>.class);

The advantage was that it could be pasted from class to class without accidentally being a logger for another class.

Now, I can't get that to compile, the syntax must be wrong. So what exactly does <> resolve to on its own (not ArrayList<>(), etc.)?

Thank you

Update:

My assertion that it is legal syntax comes from:

  1. I saw it out on the web as a legal and nifty trick.
  2. Both I and a colleague pasted it into IntelliJ with Java 7 and it compiled correctly.

That said, I can't find a search that will get me to that page again, and I can't get it to compile now! So I'm hoping someone with compiler or Java spec knowledge can definitively say if it is valid and what the default is.

1

There are 1 best solutions below

0
On

Back in Java 5 and 6, when you had to declare a new instance of a generic class*, you had to use the following syntax.

List<String> myList = new ArrayList<String>();

There was no type inference at declaration time for generics.

With the advent of Java 7, the compiler learned a trick or two about type inference.

If the compiler can infer it, then using the diamond operator <> as it's called will produce the same result in Java 7 and up as the code above:

List<String> myList = new ArrayList<>();

There are situations, of course, where it can't. This is borrowed from the linked example above.

List<String> list = new ArrayList<>();
list.add("A");
// The following statement should fail since addAll expects
// Collection<? extends String>

list.addAll(new ArrayList<>());

What you've got here is invalid code:

private static Logger log = Logger.getLogger(<>.class);

You actually need to pass a concrete Class to that method, and Java isn't going to be able to infer it for you in that context.

*: I don't recall if it was as bad with generic methods, but I didn't do a lot of development with Java 6 back in the day.