Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java object definition shorthand or shortcuts?

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.

like image 448
Brian Risk Avatar asked Apr 15 '26 00:04

Brian Risk


2 Answers

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.

like image 110
Anderson Vieira Avatar answered Apr 16 '26 12:04

Anderson Vieira


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<>();
like image 32
Michael Lang Avatar answered Apr 16 '26 12:04

Michael Lang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!