0

我正在尝试从克隆的数组中转换方法。但是,我遇到了一些问题。这是代码:

    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());

}
4

1 回答 1

0

尝试使用此代码(其完美运行)检查此链接

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
于 2013-06-15T17:33:36.900 回答