Home > Net >  How to call methods of class from inside extended ArrayList
How to call methods of class from inside extended ArrayList

Time:12-06

I want to create a custom ArrayList that can get multiple types like ArrayList<A>, ArrayList<B>.

I extended ArrayList like this:

public class ArrayListId<E> extends ArrayList {
    public ArrayListId(@NonNull Collection c) {
        super(c);
    }

    public void doSomething(){
        //some code
        String id = this.get(0).getId();
        //some code
}

both A and B have the getId method in common but this.get(index) returns an Object which doesn't have this method so I get an error. how can i achieve this without abstracting A and B classes?

CodePudding user response:

First of all, there's no need to extend ArrayList here. You can do this just fine without using inheritance.

To access the getId-method from A and B, they would need to implement a common interface that defines the method. Something like this:

interface CommonInterface {
    String getId();
}

class A implements CommonInterface { /* implement getId() */ }
class B implements CommonInterface { /* implement getId() */ }

With this, you can create an ArrayList<CommonInterface> that can contain both As and Bs.

List<CommonInterface> list = new ArrayList<>();
list.add(new A());
list.add(new B());

You can take this list as an input to a doSomething-method:

public void doSomething(List<CommonInterface> list) {
    //some code
    String id = list.get(0).getId();
    //some code
}

If you still need to extend ArrayList (you really shouldn't), then you would need to define it like this:

public class ArrayListId<E extends CommonInterface> extends ArrayList<E> {}
  • Related