2

Abstract list < Person & gt;

 3 years ago
source link: https://www.codesd.com/item/abstract-list-person.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Abstract list < Person & gt;

advertisements

Update: My classes are more complex than this, I just am stuck on the ArrayList line

I have the following classes:

class CatList {

    List<Cat> cats = new ArrayList<Cat>();

}

class DogList {

    List<Dog> dogs = new ArrayList<Dog>();

}

Where Cat and dog are both data classes.

but I want to create an abstract class:

abstract class AnimalList {

    List<???> animals;

    AnimalList(Class animal) {

        animals = new ArrayList<???>();

    }
}

so that I can inherit my classes

AnimalList CatList = new AnimalList(Cat);
AnimalList DogList = new AnimalList(Dog);
AnimalList CowList = new AnimalList(Cow);

Hopefully that makes more sense. My question is therefore What are the ??? bits?


Using a type parameter might solve your problem - using the same class for different types - without inheritance:

public class AnimalList<T> {
  private List<T> list = new ArrayList<T>();

  public void add(T animal) {
    list.add(animal);
  }
  // more methods
}

Now you can parametize instances for persons and animals:

AnimalList<Cat> catList = new AnimalList<Cat>();
catList.add(new Cat());
AnimalList<Dog> dogList = new AnimalList<Dog>();
dogList.add(new Dog());




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK