How to pass list contents to varargs method?

I have a method that uses the varargs function:

void add(Animal ...);

Now, instead of doing it .add(dog, cat), I have a list of animals with an unknown number of elements,

List<Animal> i = new ArrayList<Animal>();
i.add(dog);
i.add(cat);

and you want to call add with the elements of this list.

I think I could use an array, but when I do .add(i.toArray()), it gives a compiler error.

What is the right way to do this?

+5
source share
3 answers

It:

add(i.toArray(new Animal[i.size()]))

List.toArray Object[], : new List<String>().toArray(), Object[]. , toArray, , : new List<String>().toArray(new String[0]), String[]. , , , , , .

. , String[] List<String> - , - .

.

, . JVM, (- ) , . , - , , . , , , , .

List, , generics, Java erasure, , , , , , ( , , JVM ). ( , Java, JVM), - , , , . List toArray(), , , Object[]. .

, , List , , , a List , , ( , ( Object[] array = new String[0];)), , , .

, :

public <E> E[] createSimilarlyTypedArray(List<E> list) {
    Class<E> componentType = list.???; // there is no way to do this
    return Arrays.newInstance(componentType, list.size());
}
+10

.add(i.toArray()), , ?

foo.addAll(i), foo .

0

Your method void add(Animal...)expects an object of a class Animalor an array with Animal objects in it. You give it an array with class objects Object. Give a list such a generic type:

List<Animal> animals = new ArrayList<Animal>();
animals.add(dog);
animals.add(cat)

Then parse the list as an argument, converting it to an array, to your method:

add(animals.toArray(new Animal[animals.size()]);

More on generics can be found in the Java API.

http://download.oracle.com/javase/1,5.0/docs/guide/language/generics.html

0
source

All Articles