Java Generic query

Soldato
Joined
1 Mar 2003
Posts
5,508
Location
Cotham, Bristol
Ok given we can do this

Code:
import java.util.*;
class Animal {}
class Dog extends Animal {}
public class Generics {
   public static void main(String... args) {
      List<Animal> animalList = new ArrayList<Animal>();
      animalList.add(new Dog());
      animalList.add(new Dog());
      addAnimals(animalList);
   }
   public static void addAnimals(List<? super Dog> list) {
       list.add(new Dog());    
   }
}

What use could you get from the following generic code

Code:
List<? super Dog> animalList = new ArrayList<Animal>();

You can't afterall then say

Code:
animalList.add(new Animal());

You can only do the following

Code:
animalList.add(new Dog());

So yeah I'm curious, there's nothing wrong with the syntax of this example, it just doesn't seem to have any use?
 
Well in your example it's clearly not of any additional use, but it's obviously capable of different things because it will match any superclass of Dog. List<? super Dog> could be matched with List<Object>, List<Animal> and List<Dog>. This tutorial has some good examples of using wildcards.
 
Back
Top Bottom