crackerplace
crackerplace

Reputation: 5475

Why is List<String> accepting another <List> as an element

import java.lang.Math;
import java.util.*;
import java.io.*;


class Hello {


    public static void main(String args[]) throws FileNotFoundException{

        String[] veri2 = {"No", "Compilation", "Error"};

        List<String> veri1 = new ArrayList<String>();
        veri1.addAll(Arrays.asList(veri2)); // ---------- 14
        System.out.println(veri1+"elements in hashset");

    } 

}

Why the above code doesnt throw a compile error at line 14 when a List is added to another List whose elemnts are of type String ?

Upvotes: 2

Views: 172

Answers (8)

Thomas
Thomas

Reputation: 88707

The signature in your case is addAll(Collection<String> c) and since you pass a List<String> which extends Collection<String> all is fine.

Upvotes: 3

Jon
Jon

Reputation: 277

Because Arrays.asList() returns a List. In your case it is interpreting your String[] and setting that as the type.

Upvotes: 1

Augusto
Augusto

Reputation: 978

As you can see in the List API:

public boolean addAll(Collection c)

Appends all of the elements in the specified collection to the end of this list...

So no type error because addAll receives Collection (List is a Collection) as argument and adds them to the list.

Upvotes: 0

Michael Borgwardt
Michael Borgwardt

Reputation: 346309

Why would you expect a compiler error? The signature of addAll() is:

boolean addAll(Collection<? extends E> c)

So in your case:

boolean addAll(Collection<? extends String> c)

And Arrays.asList():

public static <T> List<T> asList(T... a)

Which means for your

public static List<String> asList(String... a)

So addAll() wants a Collection<? extends String> and gets a List<String> - which is perfectly OK.

Upvotes: 1

andrewdski
andrewdski

Reputation: 5505

Because addAll adds each element of a collection to a list. If you had called add, you presumably would have gotten the error you expected.

Upvotes: 0

Alan Escreet
Alan Escreet

Reputation: 3549

Arrays.asList() is generic and since your array is an array of String, it returns a List<String>, which is exactly what you want.

see: http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList(T...)

Upvotes: 1

Dan Tao
Dan Tao

Reputation: 128307

The List<E>.addAll method accepts a Collection<? extends E>, and the List<E> interface inherits from Collection<E>.

If you tried to add a String using addAll, you would actually get an error.

List<String> list = new ArrayList<String>();
list.addAll("Hello");

The above code wouldn't work, since String does not implement Collection<String>.

Upvotes: 8

Peter Lawrey
Peter Lawrey

Reputation: 533530

When you add all the elements of a List<String> to a List<String> this is the one occasion you shouldn't get an error.

Upvotes: 0

Related Questions