Peter Birdsall Peter Birdsall - 1 month ago 5
Java Question

I have 2 different classes that I want to add to an ArrayList what the best way to define the ArrayList?

I have class A and class D that depending on the case that I want to add to an ArrayList and later use instanceOf to determine which class is present. I'm not sure whether to use and wildcard generic

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


or define it as an Object

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

Answer

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.

Comments