[英]Java help, Creating Array of Objects
我有一个对象数组(一个名称和一个数字数组),它没有正确地在数组中存储新的对象。 每次我尝试使用for循环添加新对象时,它都会覆盖以前的对象。 请原谅我,因为我是新手,并且在这个问题上被困了好几个小时。
/////INITIALIZE THE DATA/////////
// Read the Data and Return an Array of Objects from the text File
// Read in the info and calculate number of total lines.
Scanner scanFile1 = new Scanner(new FileReader("names2.txt"));
while (scanFile1.hasNextLine())
{
scanFile1.nextLine();
lines++;
}
scanFile1.close();
// Create array of objects
Scanner scanFile2 = new Scanner(new FileReader("names2.txt"));
nameArray = new Name[lines];
String tempName;
int[] tempArray = new int[DECADES];
for (int n = 0; n < lines; n++)
{
tempName = scanFile2.next();
for (int i = 0; i < DECADES; i++)
{
tempArray[i] = scanFile2.nextInt();
}
nameArray[n] = new Name(tempName, tempArray);
System.out.println(n);
System.out.println(tempName);
System.out.println(Arrays.toString(tempArray));
System.out.println(Arrays.toString(nameArray[0].popularityRanks));
scanFile2.nextLine();
}
scanFile2.close();
当我单步执行代码时,在发生更改时打印出更改,我看到位置nameArray [0]中的项目不断加载从文本文件中读取的最新数据集。 这是文本内容供参考。
Bob 83 140 228 286 426 612 486 577 836 0 0
Sam 0 0 0 0 0 0 0 0 0 380 215
Jim 1000 999 888 777 666 555 444 333 222 111 100
这里是变化的打印输出(打印数组的索引,新名称,对象的第二部分的新数字,以及数组的位置0中的数字)
0
Bob
[83, 140, 228, 286, 426, 612, 486, 577, 836, 0, 0]
[83, 140, 228, 286, 426, 612, 486, 577, 836, 0, 0]
1
Sam
[0, 0, 0, 0, 0, 0, 0, 0, 0, 380, 215]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 380, 215]
2
Jim
[1000, 999, 888, 777, 666, 555, 444, 333, 222, 111, 100]
[1000, 999, 888, 777, 666, 555, 444, 333, 222, 111, 100]
Name类如下:
public class Name
{
public static final int DECADES = 11;
public static final int DECADE1900 = 0;
public static final int DECADE1910 = 1;
public static final int DECADE1920 = 2;
public static final int DECADE1930 = 3;
public static final int DECADE1940 = 4;
public static final int DECADE1950 = 5;
public static final int DECADE1960 = 6;
public static final int DECADE1970 = 7;
public static final int DECADE1980 = 8;
public static final int DECADE1990 = 9;
public static final int DECADE2000 = 10;
public String name = "err";
public int[] popularityRanks;
public Name (String name, int[] popularityRanks)
{
this.name = name;
this.popularityRanks = popularityRanks;
}
//...more methods to assess and work with the class...
}
提前谢谢,这个网站非常有用,我从来没有需要在这里发布,直到现在,我的最后一个任务。
问题是当你在循环外执行此操作时:
int[] tempArray = new int[DECADES];
内存中只生成一个数组。 数组在Java中被视为对象,当您将变量分配给数组时,它不会复制数组。
所以当你这样做时:
nameArray[n] = new Name(tempName, tempArray);
您正在向新名称传递对同一tempArray的新引用。 因此,当您修改它时,“所有其他数组”都被修改也就不足为奇了 - 它们实际上是相同的数组。
要解决此问题,请将数组置于for循环中,而不是将其置于for循环之外。
数组是一个对象。 如果你重新使用相同的数组,那么你将重写它。 只是在构造函数中传递它并不会使它成为新的。 它似乎只是存储对相同的对象名称:
tempArray = new int[DECADES];
你需要做什么要么:
要么
添加线
tempArray = new int[DECADES];
行后
nameArray[n] = new Name(tempName, tempArray);
有助于查看Name类的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.