[英]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). 我正在尝试创建一个类型为
TileEntity
的ArrayList
(显然是java)(是的,这是我的世界mod)。 But I also need the objects added to the ArrayList
to implement a certain interface. 但是我还需要将对象添加到
ArrayList
以实现某个接口。
The first option that came to mind was creating an abstract subclass of TileEntity
that implemented interface, and using that as the ArrayList
type. 我想到的第一个选择是创建实现接口的
TileEntity
的抽象子类,并将其用作ArrayList
类型。 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
. 但是考虑到人们通常会创建自己的
TileEntity
子类并将其用作他们通常子类的TileEntity
,并且我希望人们能够加入我的mod中,所以我不能期望他们会TileEntity
之外的TileEntity
类。
My current solution is to check if(object instanceof MyInterface)
before adding, but that seems ugly. 我当前的解决方案是在添加之前检查
if(object instanceof MyInterface)
,但这看起来很丑。 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
. 肯定有一种方法来设置一个类型
ArrayList
需要一个对象既是子类TileEntity
和实现者MyInterface
。
You can make generic the method or class where the ArrayList
is used. 您可以使使用
ArrayList
的方法或类通用。 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>();
You could add whatever methods of TileEntity
you need to your interface, and just make the ArrayList
of your interface. 您可以将所需的
TileEntity
方法添加到接口中,然后仅创建接口的ArrayList
。 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. 编辑: dcernahoschi的解决方案要好得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.