List and list in Java

ArrayList of list < InterfaceI > and list both have class objects that implement InterfaceI When should I use it?

Solution

Suppose Foo and bar are two classes that implement InterfaceI

The second (list ) does not allow anything to be added to the list (except null), because the type contained in the list is unknown: it can be list < foo > or list < bar >: you just don't know

Therefore, when you want the method to read the list elements passed as parameters, you usually use this notation for the method parameters, and you want the caller to call your method using list < InterfaceI >, list < foo > Or list < bar > Use list < InterfaceI > because the parameter only accepts lists of type list < InterfaceI >

Let's take a specific example: you want to calculate the maximum double value of a list of numbers This method does not need to add or set anything in the list It just iterates over the elements, takes each number and calculates their maximum value The signature can be

public double max(List<Number> list);

But you won't be able to do it

List<Integer> ints = new ArrayList<>();
max(ints);

The only way to call this method is to perform this operation

List<Number> ints = new ArrayList<>();
max(ints);

And if you declare a method as

public double max(List<? extends Number> list);

Then you can do it

List<Integer> ints = new ArrayList<>();
List<Long> longs = new ArrayList<>();
max(ints);
max(longs)
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
分享
二维码
< <上一篇
下一篇>>