4

I have a method that must return a Collection of Arrays. (It's a parameterized test in JUnit.) I actually only need to return three strings, but they need to be in a Collection of Arrays. This is my method:

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;
}

This gives an error: Type mismatch: cannot convert from ArrayList<String[]> to Collection<Object[]>.

So really two questions: (a) what is wrong with this, considering that ArrayList is an implementation of Collection and String is derived from Object; and (b) how would I fix it?

Thanks for any help.

aearon
  • 393
  • 4
  • 9

1 Answers1

7

For the first question, a Collection <String []> is not a Collection <Object []> because generics are not polymorphic.

For your second question, simply declare everything as objects:

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;
}

Which you could condense in:

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

    return Arrays.asList(firefox, chrome, ie);
}
Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783