Home » Java » List<Object> variable being assignment compatible with other generic Lists like List<String> in Java

List<Object> variable being assignment compatible with other generic Lists like List<String> in Java

Posted by: admin July 12, 2018 Leave a comment

Questions:

I’ve been trying to get my head around java generics for the last few days. From what I understand, Java generics are not covariant so List<Object> is not assignment compatible with other generics Lists

But here in the following program, nameAndPhone.collect() method returns a List of type List<NamePhone> and when I replace reference variable List<NamePhone> npList with List<Object> npList the program still compiles without warnings.

I tried this with a similar method returning List<String> as well, and using List<Object> reference variable did not result in any error.

Why is List<Object> assignment compatible with List<NamePhone> here?

import java.util.*;
import java.util.stream.*;

class NamePhoneEmail
{
    String name;
    String phonenum;
    String email;

    NamePhoneEmail(String n, String p, String e)
    {
        name = n;
        phonenum = p;
        email = e;
    }
}

class NamePhone
{
    String name;
    String phonenum;

    NamePhone(String n, String p)
    {
        name = n;
        phonenum = p;
    }
}

public class CollectDemo
{
    public static void main(String[] args)
    {

        ArrayList<NamePhoneEmail> myList = new ArrayList<>();
        myList.add(
            new NamePhoneEmail("Larry", "555-5555", "Larry@HerbSchildt.com"));

        myList.add(
            new NamePhoneEmail("James", "555-4444", "James@HerbSchildt.com"));

        Stream<NamePhone> nameAndPhone =
            myList.stream().map((a) -> new NamePhone(a.name, a.phonenum));

        List<NamePhone> npList = nameAndPhone.collect(Collectors.toList());
    }
}
Answers: