[英]Storing objects in array of arrays
I have got a question regarding an assignment I need to finish. 我有一个关于我需要完成的任务的问题。 Basically I need to store coordinates in their respective objects and store them in an array.
基本上,我需要将坐标存储在它们各自的对象中,并将它们存储在数组中。 There are multiple sets of coordinates which all need a separate array, all these arrays again need to be stored in an array.
有多组坐标都需要一个单独的数组,所有这些数组又需要存储在一个数组中。
This is a simple version of what I'm trying to do, using 3 classes: 这是我尝试做的一个简单版本,使用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;
}
}
When i vary the values in the arrays in the print statement it always displays the last set of coordinates inserted. 当我在print语句中更改数组中的值时,它始终显示插入的最后一组坐标。
I hope someone can explain what I'm doing wrong. 我希望有人能解释我在做什么错。
You are using the same array row
, this won't work because of passing reference instead of values. 您使用的是同一数组
row
,由于传递引用而不是值,因此无法使用。 You should create new array. 您应该创建新的数组。 Both
main[0]
and main[1]
contains the same reference 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);
} }
this is only a part of code... 这只是代码的一部分...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.