How to make an ArrayList of Classes?

前端 未结 2 821
迷失自我
迷失自我 2021-01-29 10:33

How can I add a bunch of classes to an ArrayList and then later retrieve a Class (derived from, but not MyBaseClass) from the

2条回答
  •  遥遥无期
    2021-01-29 11:06

    Here is what I think you're asking for:

    // get a list from somewhere
    List list = new ArrayList();
    
    // call list.add(...) a few times
    
    // iterate over all the objects and check their sub class with "instanceof"
    for (MyBaseClass item : list) {
        if (item instanceof MySubClass) {
            MySubClass subItem = (MySubClass) item;
            item.doThing();
        } else if (item instanceof OtherSubClass) {
            OtherSubClass subItem = (OtherSubClass) item;
            item.doThing();
        }
    }
    

    But if you find yourself needing to check if an object is the instance of a particular class, you're probably doing something wrong. Try creating an abstract method in MyBaseClass that can be implemented by each sub class in its own special way. Then, you can simplify the for loop to just this:

    for (MyBaseClass item : list) {
        item.doThing();
    }
    

提交回复
热议问题