在我的项目中,我用不同的对象填充ArrayList。
private List<Object> objectList = new ArrayList<Object>();
...
objectList.add(StudentObject);
objectList.add(ManagerObject);
objectList.add(AnimalObject);
我的每个object-class都包含一个名为getType(){}的方法,它返回一个int值。现在我想在列表中的对象上调用此方法。
objectList.get(i).getType();
这不行,可能是因为列表期望一个对象而不是每个对象类都有方法getType(); ?
但是如何避免这个问题并在列表中的对象上调用该方法?
答案 0 :(得分:0)
Object
不包含getType
您需要将其转换为对象类型。
在你首先投射之前你需要检查对象是否属于某种类型,这样你才不会崩溃
例如
if(objectList.get(i) instanceof StudentObject){
StudentObject student = (StudentObject)objectList.get(i)
student.getType();
}
答案 1 :(得分:0)
您可以定义一个定义getType()
的接口或超类,并使每个类实现或继承该接口或超类。
示例:
public interface Typed {
public int getType();
}
public class Student implements Typed {
public int getType() {
// code here
}
}
// similar definitions for other classes
// later in some other code...
List<Typed> list = new ArrayList<Typed>();
list.add(new Student());
// add other objects...
// then this...
int typei = list.get(i).getType();
// or maybe this...
for (Typed object : list) {
int type = object.getType();
// ...
}
答案 2 :(得分:0)
如果您想要实现您的要求,请将其设为您自己的包含该方法的对象的ArrayList
。
public abstract class MyTypeObject extends Object
{
abstract int getType();
}
public class MyObject1 extends MyTypeObject
{
private int type = 201;
int getType()
{
return type;
}
}
然后,不是传递对象,而是传递MyTypeObject。这会强制任何MyTypeObject具有getType()方法。然后,您可以像这样分配您的ArrayList。
private List<MyTypeObject> objectList = new ArrayList<MyTypeObject>();
然后你可以保证它有你的getType()方法,你可以访问它。
答案 3 :(得分:0)
Java中的Object
没有getType
方法。如果您在此列表中插入的所有对象都使用方法getType
,请考虑使用Interface
。然后,您可以插入接口,而不是将Objects
插入List中。
例如:
public interface MyInterface {
public int getType();
}
让每个类都实现此接口。
public class StudentObject implements MyInterface {
...
@Override
public int getType() {
...
}
...
}
现在,在您的列表中:
private List<MyInterface> objectList = new ArrayList<MyInterface>();
...
objectList.add(StudentObject);
objectList.add(ManagerObject);
objectList.add(AnimalObject);
现在,从objectList
添加的每件事都必须是MyInterface
类型。同样,从objectList
读取的所有内容都属于MyInterface
类型,您可以拨打getType
。
另一种方法是将你从objectList
中剔除的东西。