gpt4 book ai didi

java - ArrayList 和 Arrays.asList 在继承情况下对 Collection 的工作方式不同

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:01:28 27 4
gpt4 key购买 nike

public class SS {
public static void main(String[] args) {
SS s = new SS();
List<B> list = new ArrayList<>();

s.checkWithoutInheritance(Arrays.asList(new B())); //Works fine
s.checkWithoutInheritance(list); //----------Not working

s.checkWithInheritance(Arrays.asList(new B())); //Works fine
s.checkWithInheritance(list); //Works fine
}

private void checkWithInheritance(final Collection<? extends A> s) {
}

private void checkWithoutInheritance(final Collection<A> s) {
}
}


class A {
};

class B extends A {
};

最佳答案

它们的行为并没有不同,只是您以不同的方式使用它们。

这里您让编译器决定 List 的类型由 Arrays.asList 返回, 编译器决定它应该是 List<A> ,给定 checkWithoutInheritance() 所需的参数:

s.checkWithoutInheritance(Arrays.asList(new B()));

在这里你传递了一个 List<B>方法,因此编译器别无选择,只能失败:

List<B> list = new ArrayList<>();
s.checkWithoutInheritance(list);

如果您同时使用 List同样,您将获得相同的输出:

都失败了:

List<B> list = new ArrayList<>();
List<B> list2 = Arrays.asList(new B());
s.checkWithoutInheritance(list2);
s.checkWithoutInheritance(list);

两者都有效:

s.checkWithoutInheritance(Arrays.asList(new B()));
s.checkWithoutInheritance(new ArrayList<>());

至于checkWithInheritance(final Collection<? extends A> s) , 它接受 List<A>和一个 List<B> ,这就是为什么你的 checkWithInheritance调用通过编译。

关于java - ArrayList 和 Arrays.asList 在继承情况下对 Collection 的工作方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51059482/

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