Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to initialize ArrayList and HashMap?

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.

like image 548
SJ19 Avatar asked Jun 02 '26 13:06

SJ19


1 Answers

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.

like image 138
Mark Jeronimus Avatar answered Jun 04 '26 03:06

Mark Jeronimus