我有2个不同的类,我想添加到ArrayList中定义ArrayList的最佳方法是什么?

时间:2016-10-20 18:21:29

标签: java object generics arraylist

我有A类和D类,这取决于我想要添加到ArrayList的情况,然后使用instanceOf来确定存在哪个类。我不确定是否使用和通配符通用

 private ArrayList<?> mEntity = new ArrayList<>();

或将其定义为对象

 private ArrayList<Object> mEntity = new ArrayList<>();

1 个答案:

答案 0 :(得分:1)

The correct design depends on what you'll do after you take A or D typed objects from the ArrayList.

If you're doing completely different things to different A and D objects then there is no functional overlap even if they have common fields. You can still do

private ArrayList<Object> mEntity = new ArrayList<>();

But that has little help if you will process the object like

for (int i=0 ; i < mEntity.size() ; i ++=) {
    Object obj = mEntity.get(i);
    if (obj instanceOf A) {
        // Do Something
    } else if (obj instanceOf D) {
        // Do other things
    }
}

Instead of this you can easily use two ArrayList objects.

However if you have some common functionality in A and D, and you'll be using the object by this functionality then you can encapsulate this common functionality into an interface.

Assume you'll process the objects like

for (int i=0 ; i < mEntity.size() ; i ++=) {
    Object obj = mEntity.get(i);
    if (obj instanceOf A) {
        A objA = (A) obj);
        objA.workerMethod();
    } else if (obj instanceOf D) {
        D objD = (D) obj;
        objD.workerMethod();
    }
}

Then you can define an interface and use polymorphism

public interface CommonFunc {
    void workerMethod();
}

private ArrayList<CommonFunc> mEntity = new ArrayList<>();

for (int i=0 ; i < mEntity.size() ; i ++=) {
    CommonFunc obj = mEntity.get(i);
    obj.workerMethod();
}

You can do this even if there is no common method but still it has little meaning.