我正在尝试从克隆数组中转换方法。但是,我遇到了一些问题。 这是代码:
Array1[] a = new Array1[] {
"new Array1("exampletext", 0.5, 205)
};
Object[] o = a.clone();
System.out.println(o[0].getSomething());
当我使用“原始”对象时,它可以正常工作。我以为克隆的对象是一个精确的副本。 谁能告诉我那里出了什么问题或者给我一些提示?
编辑:好的,这是真正的代码(我也不能编译它!)
Drinks[] gtrk = new Drinks[] {
new Drinks("Drink1", 0.90, 205, 0.5 ),
new Drinks("Drink2", 0.90, 190, 0.5 ),
new Drinks("Drink3", 0.70, 150, 0.5 ),
new Drinks("Drink4", 20.50, 500, 2.0 ),
new Drinks("Drink5", 28.70, 360, 1.5 ),
new Drinks("Drink6", 6.90, 2500, 12.0 )
};
public void objectArrayTest() {
Object[] o = gtrk.clone();
System.out.println(o.getName());
}
答案 0 :(得分:0)
尝试使用此代码(其功能完美),请检查此LINK:
class Drinks{
String name;
int i;
double d1,d2;
public Drinks(String name, double d1, int i, double d2) {
super();
this.name = name;
this.i = i;
this.d1 = d1;
this.d2 = d2;
}
@Override
public String toString() {
return "Drinks [name=" + name + ", i=" + i + ", d1=" + d1 + ", d2=" + d2 +
"]";
}
}
public class ArrayEg {
public static void main(String[] args) {
Drinks[] gtrk = new Drinks[] {
new Drinks("Drink1", 0.90, 205, 0.5 ),
new Drinks("Drink2", 0.90, 190, 0.5 ),
new Drinks("Drink3", 0.70, 150, 0.5 ),
new Drinks("Drink4", 20.50, 500, 2.0 ),
new Drinks("Drink5", 28.70, 360, 1.5 ),
new Drinks("Drink6", 6.90, 2500, 12.0 )
};
Object[] obj = new Object[gtrk.length];
System.arraycopy(gtrk, 0, obj , 0, gtrk.length);
for(Object o:obj){
System.out.print((Drinks)o);
}
}
}
如果您需要从Drinks对象中调用一些方法,请尝试(在循环内)
((Drinks)o).method