简体   繁体   English

分配给Java中更广泛类型的不同实现之间的差异

[英]Difference between different implementations assigned to broader type in Java

I know that its considered best practice to assign subclass implementations to variables of an Interface type in order to maintain flexibility like so: 我知道将子类实现分配给Interface类型的变量是最佳实践,以保持灵活性,如下所示:

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

My current understanding is that when declaring list as type List , you limit its functionality to only implementations of methods that type List requires, and doesn't allow implementation-specific methods. 我目前的理解是,当将list声明为类型List ,将其功能限制为仅List所需的方法的实现,并且不允许特定于实现的方法。 That said, what's the difference between: 那说,有什么区别:

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

and: 和:

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

Other than some obvious performance differences caused by the different implementations of each class for the List interface, are there any differences? 除了由List接口的每个类的不同实现引起的一些明显的性能差异之外,是否有任何差异?

As another example, using Set , I know that doing: 作为另一个例子,使用Set ,我知道这样做:

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

gives you a HashSet as a Set , whereas: 给你一个HashSet作为Set ,而:

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

gives you a TreeSet as a Set which means (among other things), that set is automatically sorted. 给你一个TreeSet作为一个Set ,这意味着(除其他外),该set是自动排序的。 But isn't the automatic sorting an implementation-specific function of the class? 但是不是自动排序类的特定于实现的函数吗?

As already correctly stated in the comments, if you are declaring a variable by its interface, you only have access to the methods defined by that interface. 正如评论中已正确陈述的那样,如果您通过其接口声明变量,则只能访问该接口定义的方法。 The main difference between the concrete types resides in the performance of the implementation. 具体类型之间的主要区别在于实现的性能。

But some method defined in the interface are also optionally implemented. 但是也可以选择性地实现界面中定义的某些方法。 For example the method add of the java.util.Set interface throws an UnsupportedOperationException , if the add operation is not supported by the concrete type that implents the Set interface. 例如,如果实现Set接口的具体类型不支持add操作,则java.util.Set接口的方法add会抛出UnsupportedOperationException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM