[英]How to call methods of class from inside extended ArrayList
I want to create a custom ArrayList
that can get multiple types like ArrayList<A>
, ArrayList<B>
.我想创建一个自定义ArrayList
,它可以获得多种类型,如ArrayList<A>
、 ArrayList<B>
。
I extended ArrayList like this:我这样扩展了 ArrayList:
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. A
和B
都有共同的getId
方法,但是 this.get this.get(index)
返回一个Object
没有这个方法,所以我得到一个错误。 how can i achieve this without abstracting A
and B
classes?我如何在不抽象A
和B
类的情况下实现这一目标?
First of all, there's no need to extend ArrayList
here.首先,这里不需要扩展ArrayList
。 You can do this just fine without using inheritance.您可以在不使用 inheritance 的情况下完成此操作。
To access the getId
-method from A
and B
, they would need to implement a common interface that defines the method.要从A
和B
访问getId
方法,他们需要实现一个定义该方法的通用接口。 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.有了这个,您可以创建一个可以包含 As 和 Bs 的ArrayList<CommonInterface>
。
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:您可以将此列表作为doSomething
方法的输入:
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:如果你仍然需要扩展ArrayList
(你真的不应该),那么你需要像这样定义它:
public class ArrayListId<E extends CommonInterface> extends ArrayList<E> {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.