将对象存储在数组数组中

时间:2014-11-15 15:12:14

标签: java arrays object

我有一个关于我需要完成的任务的问题。基本上我需要在各自的对象中存储坐标并将它们存储在一个数组中。有多组坐标都需要一个单独的数组,所有这些数组都需要存储在一个数组中。

这是我尝试做的简单版本,使用3个类:

package test2;

import java.io.PrintStream;
//import java.util.Scanner;


public class Test {

PrintStream out;

Test(){
    out = new PrintStream(System.out);
}

    Coordinate[] row = new Coordinate[5];
    CoordinateRow[] main = new CoordinateRow[10];

    void start(){


    row[0] = new Coordinate(4, 9);
    row[1] = new Coordinate(4, 1);
    row[2] = new Coordinate(0, 4);

    main[0] = new CoordinateRow(row);


    row[0] = new Coordinate(5, 3);
    row[1] = new Coordinate(7, 2);
    row[2] = new Coordinate(4, 8);


    main[1] = new CoordinateRow(row);

    out.println(main[0].row[0].y);




    }

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    new Test().start();
}

}




package test2;


public class Coordinate{

    int x;
    int y;

    Coordinate(int x, int y){

        this.x = x;
        this.y = y;     

    }

}

package test2;

import test2.Coordinate;


public class CoordinateRow {

    Coordinate[] row;

    CoordinateRow(Coordinate[] row){
        this.row = row;

    }
}

当我改变print语句中数组中的值时,它总是显示插入的最后一组坐标。

我希望有人可以解释我做错了什么。

1 个答案:

答案 0 :(得分:0)

您正在使用相同的数组row,由于传递了引用而不是值,因此无法工作。你应该创建新的数组。 main[0]main[1]都包含相同的引用

SubClass[] row = new SubClass[5];
SubClass[] row2 = new SubClass[5];
SubClass2[] main = new SubClass2[10];

void start(){


row[0] = new SubClass(4, 9);
row[1] = new SubClass(4, 1);
row[2] = new SubClass(0, 4);

main[0] = new SubClass2(row);


row2[0] = new SubClass(5, 3);
row2[1] = new SubClass(7, 2);
row2[2] = new SubClass(4, 8);


main[1] = new SubClass2(row2);

out.println(main[0].row[0].y);

}

这只是代码的一部分......

相关问题