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.
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.
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<>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With