Let's say I want to create an ArrayList for numbers. The way I learned it is like this:
private static List<Integer> numbers = new ArrayList<Integer>();
But IntelliJ IDEA wants to correct it to
private static List<Integer> numbers = new ArrayList<>();
And then I found out this works as well:
private static List<Integer> numbers = new ArrayList();
Now I'm confused, what's the best way? And what's the difference. Same question applies to HashMap.
The best way is:
private static List<Integer> numbers = new ArrayList<>(); // Java 7
private static List<Integer> numbers = new ArrayList<Integer>(); // Java 6
Lets take a look at the other examples:
private static ArrayList<Integer> numbers = new ArrayList<Integer>(); uses a specific class as the type, which is discouraged unless you need to access ArrayList-specific methods (I don't know any)
private static ArrayList<Integer> numbers = new ArrayList(); is type-unsafe, and your IDE should give you a warning on this line.
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