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

I want to pass some ArrayList<Integer>

X to a method a(Collection<Integer> someCol)

that takes Collection<Integer>

as input.

How can i do this? I thought ArrayList was a collection and so I had to "just do it", but it seems that Collection is an interface and ArrayList implements that interface. Is there something I can do to make this work ... if you understand the theory that will help me and possibly many other people as well.

thanks

+2


a source to share


2 answers


Just do it.

Seriously, the class will be implicitly cast into the interface for which it is being implemented.



Edit
If you want 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);
    }
}
      

+9


a source


class ArrayList<E> implements List<E>

and interface List<E> extends Collection<E>

therefore ArrayList<Integer>

is-a Collection<Integer>

.

This is what is called "subtyping".

Note that though Integer extends Number

, List<Integer>

is-not-a List<Number>

. It is, however, a List<? extends Number>

. That is, generics in Java are invariant; it is not covariant.

Arrays, on the other hand, are covariant. A Integer[]

is-a Number[]

.



Links

Related questions

+4


a source







All Articles