jrc*_*03c 0 java processing arraylist
在Processing中,我有一个从自定义类构建的对象的ArrayList.当我使用该.get()函数返回其中一个对象时,它似乎可以正确返回对象 - 但我无法访问任何对象的变量或方法.我收到错误消息"[变量]无法解析或不是字段." 这是一个错误,还是我做错了什么?
这是一个样本.注意函数返回的值setup().
// regular array
Thing[] thinglist1 = new Thing[1];
// ArrayList array
ArrayList thinglist2 = new ArrayList<Thing>(1);
// instantiate the class
Thing thing = new Thing(12345);
// class definition
class Thing {
int var;
Thing(int i){
var = i;
thinglist1[0] = this;
thinglist2.add(this);
};
};
// run it!
void setup(){
println(thinglist1[0] == thinglist2.get(0));
// true
println(thinglist1[0].var);
// 12345
println(thinglist2.get(0).var);
// ERROR: "var cannot be resolved or is not a field"
};
Run Code Online (Sandbox Code Playgroud)
你有点搞砸了你的仿制品.
更改
ArrayList thinglist2 = new ArrayList<Thing>(1);
Run Code Online (Sandbox Code Playgroud)
至:
ArrayList<Thing> thinglist2 = new ArrayList<Thing>(1);
Run Code Online (Sandbox Code Playgroud)
因为你没有指定类型,你真正拥有的是:
ArrayList<? extends Object> thinglist2 = new ArrayList<Thing>(1);
Run Code Online (Sandbox Code Playgroud)
所以当你使用get它从中检索一个项目时,它被输入Object而不是你的Thing
编辑添加:原因是遗产; 当引入仿制药时,为了向后兼容,已经制定了一些东西.不幸的是,这会产生这样的情况,这对Java新手来说很困惑.
你可能期望编译器警告或错误,但是Java默默地将非泛型类型ArrayList转换为"包含扩展Object的东西的Arraylist"......这是任何东西(除了原语),因为所有对象都隐式地扩展Object