Java 如何将 ArrayList 传递给将集合作为输入的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2778592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:45:25  来源:igfitidea点击:

How do I pass an ArrayList to method that takes a collection as an input

javaarraylistcollectionsinterface-implementation

提问by Ankur

I want to pass some ArrayList<Integer>X into method a(Collection<Integer> someCol)that takes Collection<Integer>as an input.

我想通过一些ArrayList<Integer>X进入方法a(Collection<Integer> someCol)是采用Collection<Integer>作为输入。

How can I do this? I thought an ArrayList was a Collection and thus I should be able to "just do it" but it seems that Collection is an interface and ArrayList implements this interface. Is there something I can do to make this work ... if you understand the theory that would also help me and possibly lots of other people.

我怎样才能做到这一点?我认为 ArrayList 是一个集合,因此我应该能够“做到这一点”,但似乎 Collection 是一个接口,而 ArrayList 实现了这个接口。有什么我可以做的事情吗……如果你理解这个理论,它也会帮助我,可能还有很多其他人。

Thanks

谢谢

采纳答案by Gunslinger47

Just do it.

去做就对了。

Seriously, a class will implicitly cast to an interface for which it implements.

说真的,一个类将隐式转换为它实现的接口。

Edit
In case you needed an example:

编辑
如果您需要一个示例:

import java.util.*;

public class Sandbox {
    public static void main(String[] args) {
        final ArrayList<Integer> list = new ArrayList<Integer>(5);
        Collections.addAll(list, 1, 2, 3, 4, 5);
        printAll(list);
    }

    private static void printAll(Collection<Integer> collection) {
        for (Integer num : collection)
            System.out.println(num);
    }
}

回答by polygenelubricants

class ArrayList<E> implements List<E>and interface List<E> extends Collection<E>, so an ArrayList<Integer>is-a Collection<Integer>.

class ArrayList<E> implements List<E>并且interface List<E> extends Collection<E>,所以是一个ArrayList<Integer>is-a Collection<Integer>

This is what is called "subtyping".

这就是所谓的“子类型化”。

Note, however, that even though Integer extends Number, a List<Integer>is-not-a List<Number>. It is, however, a List<? extends Number>. That is, generics in Java is invariant; it's not covariant.

但是请注意,即使Integer extends Number, a List<Integer>is-not-a List<Number>。然而,它是一个List<? extends Number>. 也就是说,Java 中的泛型是不变的;它不是协变的。

Arrays on the other hand, are covariant. An Integer[]is-a Number[].

另一方面,数组是协变的。一个Integer[]is-a Number[]

References

参考

Related questions

相关问题