sasha
sasha

Reputation: 1

In Java, list of different classes?

I've got abstract class Subject, then classes Subject1, Subject2 etc. which extend Subject.

Instead of writing if subject==1 then, else if subject==2 then etc

I want to use some kind of list, where on entering an index, would return me a subject

thanks

Upvotes: 0

Views: 1705

Answers (3)

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74790

Do you want to create new objects on demand, or select from existing ones?

If the last, use a List<Subject> like Joshc1107 proposed.

If the first, you in fact want a factory:

public interface SubjectFactory {
    public Subject create(int type);
}

... or maybe a list of such factories (then you don't need the type):

interface SubjectFactory {
    public Subject create();
}

List<SubjectFactory> factories = Arrays.asList(
      null, // we don't have type 0
      new SubjectFactory() { public Subject create() {
           return new Subject1();
      }},
      new SubjectFactory() { public Subject create() {
           return new Subject2();
      }},
      new SubjectFactory() { public Subject create() {
           return new Subject3();
      }},
      new SubjectFactory() { public Subject create() {
           return new Subject4();
      }});

public Subject create(int type) {
    return factories.get(type).create();
}

Upvotes: 2

josh-cain
josh-cain

Reputation: 5226

You can use an ArrayList<Subject>, as defined here. It's one I personally go to often, and it allows you to get items by index using the get(int index) command.

Upvotes: 0

DarthVader
DarthVader

Reputation: 55062

that s called a map , table, hashtable, dictionary, assocative array.

Upvotes: 0

Related Questions