开发者

In Java, list of different classes?

I've got abstract class Subject, then classes Subject1, Subject2 etc. which exten开发者_如何学JAVAd 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


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();
}


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜