gpt4 book ai didi

java - 相同的方法调用,LinkedList、Queue 与 List 中的不同结果

转载 作者:行者123 更新时间:2023-12-04 00:50:01 25 4
gpt4 key购买 nike

我已阅读线程 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:

  1. 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.

注意强调的部分,这意味着编译器将 1int 匹配。由于有一个适用的方法 remove(int),因此选择了该方法进行调用。换句话说,首先考虑原始类型,然后再考虑引用类型,例如 Integer(int 的装箱类型)。

关于java - 相同的方法调用,LinkedList、Queue 与 List 中的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67303404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com