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

Ankur picture Ankur · May 6, 2010 · Viewed 26k times · Source

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

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.

Thanks

Answer

Gunslinger47 picture Gunslinger47 · May 6, 2010

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