Java – the best way to initialize ArrayList and HashMap?

Suppose I want to create an ArrayList for numbers The way I learn it is this:

private static List<Integer> numbers = new ArrayList<Integer>();

But IntelliJ idea wants to correct it

private static List<Integer> numbers = new ArrayList<>();

Then I found that this also works:

private static List<Integer> numbers = new ArrayList();

Now I'm confused. What's the best way? What's the difference? The same question applies to HashMap

Solution

The best way is:

private static List<Integer> numbers = new ArrayList<>(); // Java 7
private static List<Integer> numbers = new ArrayList<Integer>(); // Java 6

Let's look at other examples:

private static ArrayList< Integer> numbers = new ArrayList< Integer>(); Using specific classes as types is discouraged unless you need access to ArrayList specific methods (I don't know)

private static ArrayList< Integer> numbers = new ArrayList(); Is type unsafe, your ide should give you a warning in this line

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>