8

"Refer to objects by their interfaces" is a good practise, as mentioned in Effective Java. So for example i prefer

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

over

ArrayList<String> al = new ArrayList<String>();

in my code. One annoying thing is that if i type ArrayList<String> al = new and then hit Ctrl+Space in Eclipse i get ArrayList<String>() as propostal. But if i type List al = new and then hit Ctrl+Space i will get only propostal to define anonymous inner class, but not propostals such as new ArrayList<String>(), what is 99% the case, or for example new Vector<String>().

Question: Is there any way to get the subclasses as propostals for generic types?

AvrDragon
  • 7,139
  • 4
  • 27
  • 42

3 Answers3

9

I would suggest simply writing the expression first and then hitting Ctrl+2, L. Then you can name the variable, followed by Enter, Down, Enter. Done.

Ben Schulz
  • 6,101
  • 1
  • 19
  • 15
  • But it looks like that fills in the variable type as `ArrayList` instead of `List` for example (so you get the same result). – Paul Bellora Jul 03 '12 at 17:13
  • @PaulBellora: You missed the key sequence, which selects the second suggestion in the list of suggested types for the variable. And that should be List, where ArrayList would be the first. – Bananeweizen Jul 03 '12 at 17:43
2

Depending on your personal style of writing such code, this is an alternative inspired by the answer of @Ben Schulz. If you typically write the assignment first like

al = new ArrayList<String>();

then you can use Ctrl+1 to start the "Create local variable" quick fix. Hitting Tab will now directly open the type selection where you select the List type.

Bananeweizen
  • 21,797
  • 8
  • 68
  • 88
2

JDK 1.7 doesn't need to specify the generic type at the right of the equal. Preference -> Java -> Compiler to 1.6