Will Fancher
Will Fancher

Reputation: 245

Create arraylist of class and interface

I'm attempting to create an ArrayList (so java, obviously) with type TileEntity (yes this is a minecraft mod). But I also need the objects added to the ArrayList to implement a certain interface.

The first option that came to mind was creating an abstract subclass of TileEntity that implemented interface, and using that as the ArrayList type. But given the fact that people normally create their own subclasses of TileEntity and use those as the class they normally subclass, and I want people to be able to hook into my mod, I can't expect them to subclass anything besides TileEntity.

My current solution is to check if(object instanceof MyInterface) before adding, but that seems ugly. Surely there's a way to set the type of an ArrayList to require that an object be both a subclass of TileEntity and an implementor of MyInterface.

Upvotes: 2

Views: 3625

Answers (2)

dcernahoschi
dcernahoschi

Reputation: 15240

You can make generic the method or class where the ArrayList is used. For example, a generic method:

public <T extends TileEntity & MyInterface> void doStuffWith(T obj) {
    List<T> yourList = new ArrayList<T>();
    yourList.add(obj);
    ...//more processing
}

And a generic class:

public class ArrayListProcessor<T extends TileEntity & MyInterface> {
   List<T> theList;

   public void processList(T obj) {
      theList.add(obj);
      ...
   }

   public void someOtherMethod() {
      T listElem = theList.get(0);
      listElem.callMethodFromTileEntity();//no need to cast
      listElen.callMethodFromMyInterface();//no need to cast
   }
}

...//somewherein your code
//SomeObj extends TileEntity and implements MyInterface 
ArrayListProcessor<SomeObj> proc = new ArrayListProcessor<SomeObj>(); 

Upvotes: 6

Nora Powers
Nora Powers

Reputation: 1607

You could add whatever methods of TileEntity you need to your interface, and just make the ArrayList of your interface. There is probably some fancy way of using generics to solve the problem in a better way, but I'm unsure how.

EDIT: dcernahoschi's solution is much better.

Upvotes: 0

Related Questions