我的部分代码有问题,我想将索引为0的空字符串与不包含索引的空行分开。尽管只需要该行的索引和元素1的整数或元素1和0之间的差。我决定使用两个链接列表来拆分每种类型的行,但结果却很奇怪。莫名其妙地将一行添加到错误的链接列表中。
void Splitter () {
String[][] databaseSchedule = {
{"", "100", "129 East Fremont St, Las Vegas, NV 89101"},
{"", "50", "770 N Las Vegas Blvd, Las Vegas, NV 89101"},
{"", "300", "1610 E Tropicana Ave, Las Vegas, NV 89119"},
{"1300", "1400", "755 E Flamingo Rd, Las Vegas, NV 89119"},
{"", "200", "4650 Aspen Ave Mt Charleston, NV 89124"},
};
int[] subArray = new int[2];
List<int[]> anyTimeStart = new LinkedList<>();
List<int[]> strictTimeStart = new LinkedList<>();
try {
for (int i = 0; i < databaseSchedule.length; ++i) {
if ("".equals(databaseSchedule[i][0])) {
subArray[0] = i;
subArray[1] = Integer.parseInt(databaseSchedule[i][1]);
anyTimeStart.add(subArray);
}
else {
subArray[0] = i;
subArray[1] = Integer.parseInt(databaseSchedule[i][1]) -
Integer.parseInt(databaseSchedule[i][0]);
strictTimeStart.add(subArray);
System.out.println(Arrays.toString(strictTimeStart.get(0)));
//Prints out [3, 100] which is expected.
}
}
System.out.println(Arrays.toString(strictTimeStart.get(0)));
//Prints out [4, 200], what happened?
} catch (NumberFormatException ex) {
System.out.println("String cannot be converted to integer");
}
}
答案 0 :(得分:0)
您只有一个数组实例:
int[] subArray = new int[2];
您将其添加到两个列表中。调用list.add(subArray)
不会将subArray
的副本添加到列表中。它将对subArray
变量引用的同一数组添加引用。因此,两个列表最终都包含对同一数组的多个引用。
在添加到列表之前创建一个新数组。例如:
for (int i = 0; i < databaseSchedule.length; ++i) {
subArray = new int[2];
if ("".equals(databaseSchedule[i][0])) {
subArray[0] = i;
subArray[1] = Integer.parseInt(databaseSchedule[i][1]);
anyTimeDuration.add(subArray);
} else {
subArray[0] = i;
subArray[1] = Integer.parseInt(databaseSchedule[i][1]) -
Integer.parseInt(databaseSchedule[i][0]);
strictTimeDuration.add(subArray);
System.out.println(Arrays.toString(strictTimeDuration.get(0)));
}
}
答案 1 :(得分:0)
您总是在两个列表中添加相同的对象:subArray
。在循环内声明并初始化:
...
for (int i = 0; i < databaseSchedule.length; ++i) {
int[] subArray = new int[2];
...
}
...