xxx222
xxx222

Reputation: 3244

How could a List contains different types in java?

I am learning Java Generics and wildcards, knowing that for a List<>, we always allow only one type across all the elements it contains. However, when I write the code this way (maybe known as producer-extend and consumer-super?), multiple types are allowed to exist in the list I created!

Did I misunderstand something about the term type safe? Actually, I found it really confusing why I have to do the producer-extend and consumer-super.

public static void wildcard(List<? super Integer> list) {
        list.add(1); 
    } 

    public static void main(String[] args) {
        List<Object> list = new ArrayList<>();
        list.add("String");
        wildcard(list);

        System.out.println(list);
    }

[String, 1]

Upvotes: 4

Views: 5029

Answers (2)

Louis Wasserman
Louis Wasserman

Reputation: 198103

Sure, there's nothing special about that. You have a List<Object>. You can write

Object a = "String";
Object b = 1;

...demonstrating an Object can be a String or an Integer, just like a List can be an ArrayList or a LinkedList. A List<Object> can hold all kinds of objects. Using a List<Object> is essentially telling the compiler that this can contain any kind of object, and you're willing to accept the associated type safety issues.

Upvotes: 7

Bathsheba
Bathsheba

Reputation: 234715

No you don't misunderstand.

All the type safety is removed at runtime by a process called type erasure. So any list can store anything inherited from Java.lang.object.

Generics allow a measured amount of type safety. ? allows a sort of half-way house.

Upvotes: -3

Related Questions