4

Possible Duplicate:
Double brace initialisation (anonymous inner class) with diamond operator

Using Java 7, why is the following a problem

final List<String> a = new ArrayList<>() {
    {
        add("word");
    }
};

Explicit type declaration is needed as in

final List<String> a = new ArrayList<String>() {
    {
        add("word");
    }
};
Community
  • 1
  • 1
James Raitsev
  • 92,517
  • 154
  • 335
  • 470
  • Diamond for anonymous class is not supported due to some technicality https://stackoverflow.com/questions/7214069/compile-error-cannot-be-used-with-anonymous-classes – irreputable Oct 12 '12 at 17:21

1 Answers1

4

IMHO, In general, Java avoids type inference.

In any case, the <> only works when the compiler doesn't need to know which generic type was used. In the case of the anonymous classes, the actual type needs to be provided as the compiler doesn't infer the type.

Effectively <> turns off the type checking, rather than providing type inference. An anonymous class stores the actual generic type and so you have to provide it.

List<String> a = new ArrayList<>()

is rather like

@SuppressWarnings("unchecked")
List<String> a = new ArrayList()

but for an anonymous subclass the compiler needs to give it a generic type.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    +1 Hm, I was absolutely convinced `<>` was about inference! The way it works for a factory method. – Marko Topolnik Oct 12 '12 at 15:45
  • 1
    diamond isn't raw typing. it does type inference and type checking. – irreputable Oct 12 '12 at 17:26
  • @irreputable Can you give an example where `<>` checks something or infers the type? – Peter Lawrey Oct 12 '12 at 18:27
  • 2
    it becomes more obvious if the type variable has bounds. e.g. if we have `class NumList extends ArrayList{}`, then `List list = new NumList<>();` won't compile, because inference fails. but raw typing works: `List list = new NumList();` – irreputable Oct 12 '12 at 20:32