我已阅读线程 Difference in LinkedList, queue vs list , 但仍然不理解以下代码行为:
List<Integer> l = new LinkedList<>();
l.add(10);
l.add(12);
l.remove(1); // removes index 1
System.out.println(l); // outputs [10]
Queue<Integer> q2 = new LinkedList<>();
q2.add(10);
q2.add(12);
q2.remove(1); // tries to remove object 1
System.out.println(q2); // outputs [10, 12]
我知道,为什么输出不同:
- 在
l
的情况下,调用remove(1)
删除索引为1
的元素
- 在
q
的情况下,调用remove(1)
尝试删除对象1
,但只有整数10
和12
。
如果我仔细看看接口(interface):
- Queue没有
remove(int)
方法,但从 Collection 继承了remove(Object)
方法. - List有一个
remove(int index)
和remove(Object o)
方法。
到目前为止,还不错。
但是:我不明白,Java 如何能够在使用相同语法 (remove(1)
) 的同时调用两种不同的方法?
最佳答案
对于List
,编译器根据method signature选择remove(int)
:
The process of determining applicability begins by determining the potentially applicable methods (§15.12.2.1). Then, to ensure compatibility with the Java programming language prior to Java SE 5.0, the process continues in three phases:
- The first phase performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.
注意强调的部分,这意味着编译器将 1
与 int
匹配。由于有一个适用的方法 remove(int)
,因此选择了该方法进行调用。换句话说,首先考虑原始类型,然后再考虑引用类型,例如 Integer
(int
的装箱类型)。
关于java - 相同的方法调用,LinkedList、Queue 与 List 中的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67303404/