2

Is there a faster way to instantiate objects in Java where one does not have to retype the class? For example, look at this tome of an instantiation:

HashMap<Integer, ArrayList<ActivityRecord>> days = new HashMap<Integer, ArrayList<ActivityRecord>>();

I'd love a shorthand that was along the lines of:

HashMap<Integer, ArrayList<ActivityRecord>> days = new();

Alternately, I'd also be happy with an Eclipse shortcut that auto-completed the instantiation to use the no-parameter constructor.

Anderson Vieira
  • 8,919
  • 2
  • 37
  • 48
Brian Risk
  • 1,244
  • 13
  • 23
  • 1
    Often you will declare the variable type to be an `interface` type, but instantiate it with a real class, e.g. `Map> = new HashMap<>();`. So the right side of the equality _needs_ to have the class being instantiated. – GriffeyDog Mar 18 '15 at 14:19
  • @pbabcdefp Indeed, updated my comment. – GriffeyDog Mar 18 '15 at 14:22

3 Answers3

8

If you are using Java 7 and above you can use the diamond operator:

HashMap<Integer, ArrayList<ActivityRecord>> days = new HashMap<>();

Also, when declaring your variables it is good practice to use the interfaces when possible, instead of the concrete classes. So the above would really be:

Map<Integer, List<ActivityRecord>> days = new HashMap<>();

If you are using Java 6, you can do this using Google Guava:

Map<Integer, List<ActivityRecord>> days = Maps.newHashMap();

For further reading, you can check the section on Type Inference and Instantiation of Generic Classes in the Type Inference documentation.

Anderson Vieira
  • 8,919
  • 2
  • 37
  • 48
2

You should the Java 7 diamond operator because often you'll be coding to the interface and not using the same class for the reference and the instance.

Map<Integer, ArrayList<ActivityRecord>> days = new HashMap<>();
Michael Lang
  • 3,902
  • 1
  • 23
  • 37
2

If you're using Java 6 (or earlier) then Google Guava comes in handy

Map<Integer, List<ActivityRecord>> days = Maps.newHashMap();
Steve Kuo
  • 61,876
  • 75
  • 195
  • 257