Java 如何从同一类中的列表内的对象访问属性?
我想从初始化对象的类中访问对象的变量。我尝试过使用objectName.atrr,也尝试过使用get方法。当我键入“testObject”时,使用这两种方法。atributes不会显示在可能性列表中,get方法也不会显示为选项。 如何从同一类中的列表内的对象访问属性Java 如何从同一类中的列表内的对象访问属性?,java,class,object,constructor,attributes,Java,Class,Object,Constructor,Attributes,我想从初始化对象的类中访问对象的变量。我尝试过使用objectName.atrr,也尝试过使用get方法。当我键入“testObject”时,使用这两种方法。atributes不会显示在可能性列表中,get方法也不会显示为选项。 如何从同一类中的列表内的对象访问属性 public class State{ // This is the constuctor Point sPos; int sID; int sRot; List listState = new ArrayList();
public class State{
// This is the constuctor
Point sPos;
int sID;
int sRot;
List listState = new ArrayList();
public ClassName(Point shape_Pos, int shape_ID, int shape_Rot){
sPos = shape_Pos;
sID = shape_ID;
sRot = shape_Rot;
}
//here are the get methods
public int getID() {
return sID;
}
public Point getPos() {
return sPos;
}
public int getRot(){
return sRot;
}
public void methodName(){
//here is code that creates States and add it to listState (left it out)
currentState.add(new State(new Point(0,0),1,1));
...
Object testObject = currentState.get(0);
System.out.println("testObject = "+testObject);
//This is not working
int id = testObject.sID;
// This is also not working
int id2 = testObject.getID();
}
}
OUTPUT://与我期望和想要的一样,与列表中的对象相同
Object = State@1ae73783
从使用泛型开始:
List<State> listState = new ArrayList<>();
当您将
testObject
声明为Object testObject=currentState.get(0)时代码>,您告诉编译器将testObject
作为Object
的实例进行处理。它将无法访问State
testObject.sID的任何成员或方法,因此假设代码中的所有内容都正常工作,代码仍将出错。谢谢!我尝试使用State,但出现了一个错误,因为我忘了将其作为一个列表。我真是有点傻;)。现在可以了@user2173361如果答案有效,你应该将其标记为正确。我必须等待7分钟才能单击正确的符号。现在我做对了?
State testObject = currentState.get(0);