Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

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 ?

like image 887
crackerplace Avatar asked Jan 27 '26 22:01

crackerplace


1 Answers

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>.

like image 200
Dan Tao Avatar answered Jan 29 '26 12:01

Dan Tao