从ArrayList <String []>转换为Collection <Object []>?

aea*_*ron 4 java junit junit4

我有一个方法必须返回一个数组集合.(这是JUnit中的参数化测试.)实际上我只需要返回三个字符串,但它们需要在一个数组集合中.这是我的方法:

public static Collection<Object[]> browserList() {
    String[] firefox = { "firefox" };
    String[] chrome = { "chrome" };
    String[] ie = { "ie" };
    ArrayList<String[]> list = new ArrayList<String[]>(3);
    list.add(firefox);
    list.add(chrome);
    list.add(ie);
    return list;
}
Run Code Online (Sandbox Code Playgroud)

这给出了一个错误:Type mismatch: cannot convert from ArrayList<String[]> to Collection<Object[]>.

所以真的有两个问题:(a)这有什么问题,考虑到这ArrayList是一个实现CollectionString从中衍生而来Object; (b)我该如何解决?

谢谢你的帮助.

ass*_*ias 7

对于第一个问题,a Collection <String []>不是Collection <Object []>因为泛型不是多态的.

对于第二个问题,只需将所有内容声明为对象:

public static Collection<Object[]> browserList() {
    Object[] firefox = { "firefox" };
    Object[] chrome = { "chrome" };
    Object[] ie = { "ie" };
    ArrayList<Object[]> list = new ArrayList<Object[]>(3);
    list.add(firefox);
    list.add(chrome);
    list.add(ie);
    return list;
}
Run Code Online (Sandbox Code Playgroud)

你可以浓缩的:

public static Collection<Object[]> browserList() {
    Object[] firefox = { "firefox" };
    Object[] chrome = { "chrome" };
    Object[] ie = { "ie" };

    return Arrays.asList(firefox, chrome, ie);
}
Run Code Online (Sandbox Code Playgroud)