Differences between different implementations assigned to a wider range of types in Java

I know that assigning subclass implementations to variables of interface type is a best practice to maintain flexibility, as follows:

List<Integer> list = new ArrayList<Integer>();

My current understanding is that when a list is declared as a type list, its function is limited to listing only the implementation of the methods required by the list, and implementation specific methods are not allowed What's the difference

List<Integer> list = new ArrayList<Integer>();

And:

List<Integer> list = new LinkedList<Integer>();

Apart from some obvious performance differences caused by different implementations of each class of the list interface, are there any differences?

As another example, using set, I know to do this:

Set<String> set = new HashSet<String>();

Give you a HashSet as a set, and:

Set<String> set = new TreeSet<String>();

Give you a TreeSet as a collection, which means (among other things) that the collection is sorted automatically But isn't it an implementation specific function that automatically sorts classes?

Solution

As stated correctly in the comments, if you declare a variable through its interface, you can only access the methods defined by that interface The main difference between specific types is the performance of the implementation

However, some methods defined in the interface can also be selectively implemented For example, if the specific type that implements the set interface does not support the add operation, Java util. The method add of the set interface throws an unsupported operationexception

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
分享
二维码
< <上一篇
下一篇>>