Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics with Collection

Question 1: Given:

  List<Object> lo = new ArrayList<Object>();

if I understand correctly, the parameter in ArrayList<>() must be Object, so do we need to write it? Or we just skip it like this:

List<Object> lo = new ArrayList<>();   

Question 2: Given:

List<? extends Animal> myArray = new ArrayList<Dog>();  

as I understand, the left side of = means myArray is a reference of List type, which can be List<Cat> or List<Dog>, .... What about the right side of =, what does it mean? Does it mean that the reference myArray is assigned to an real object of List which contains only Dog? If yes, I can't not think about a situation when the information in the right side of = is useful or necessary. Can you give me an example where

     ... = new ArrayList<Dog>();  

is essential or at least useful?

like image 240
Huy Than Avatar asked Mar 17 '26 01:03

Huy Than


1 Answers

First question: Java 7 introduces the diamond operator, which acts as syntactic sugar for writing out the full types of generics in most cases. It can be omitted, but it's "still there".

Second question:

  • The left side is a list that is an upper-bounded generic wildcard. It contains any object that either extends or implements a class named Animal. You won't be able to insert any values into that list unless the list is defined instead as a lower-bounded generic wildcard (using the super keyword). There's a fair bit more on how to use them, when to use them, and how to categorize them in this Java Trail.

  • The right side is a bit unusual to be dangling there, but it can be used to assign to an upper-bound generic type list, if you populate the list you want first.

    List<? extends Animal> fooList = new ArrayList<>();
    List<Dog> barList = new ArrayList<>();
    barList.add(new Dog());
    barList.add(new Dog());
    barList.add(new Dog());
    barList.add(new Dog());
    
    fooList = barList;
    

    You would still have to iterate over it as the upper-bound generic type:

    for(Animal d : fooList) {
        d.walk();
        d.talk();
    }
    

Essentially, the way you have it now is both misleading and not helpful, since that new ArrayList<Dog> is empty, and can't be added to.

like image 92
Makoto Avatar answered Mar 18 '26 14:03

Makoto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!