user63904
user63904

Reputation:

How to pass generic collections to methods

How do pass a generic collection of objects to my methods as detailed below:

class Test {
    class X<T> {

    }

    class XI extends X<Integer> {

    }

    class XD extends X<Double> {

    }

    class S {
        Collection<X<?>> items;

        public void addX(Iterable<X<?>> x) {
            // Error: The method addAll(Collection<? extends Test.X<?>>)
            // in the type Collection<Test.X<?>>
            // is not applicable for the arguments (Iterable<Test.X<?>>)
            items.addAll(x);
        }
    }

    void fooo() {
        X<?>[] x = new X<?>[] {new XI(), new XD()};

        S s = new S();
        // The method addX(Iterable<Test.X<?>>)
        // in the type Test.S is not applicable for the arguments (Test.X<?>[])
        s.addX(x);
    }
}

Thanks

Upvotes: 0

Views: 108

Answers (1)

Vincent Mimoun-Prat
Vincent Mimoun-Prat

Reputation: 28541

Collection.addAll expects a Collection but you pass it an Iterable ...

You can convert your array to a List (which is a Collection) by using the Arrays class:

Arrays.asList(myArray);

Upvotes: 1

Related Questions