我不认为这两个循环正在做你认为的那样。在第一个循环中,您应该消除具有相同数字的Cars,也许将它们设置为null:
for (int i = 0; i < this.cars.length; i++) {
if (this.cars[i] != null && this.cars[i].getCarNum() == CarNum) {
this.cars[i] == null;
} else {
count++;
}
}
现在这将消除重复,并保留唯一Cars 的计数。在第二个循环中,只填写非null 值:
CarsLines [] newArr= new CarLines[count];
int index = 0;
for(int i = 0; i< this.cars,length; i++)
{
if (this.cars[i] != null) { // Only pass in the non-null values
newArr[index] = this.cars[i];
index++;
}
}
this.cars= newArr;
在您创建几乎相同的列表副本之前,因为您是在一对一的基础上填写的,即相同的索引。
另一种可能的方法是就地转换:
for (int i = 0; i < this.cars.length; i++) {
if (this.cars[i] != null && this.cars[i].getCarNum() == CarNum) {
for (int j = i+1; j < this.cars.length; j++) { // This loop will shift the
this.cars[j-1] = this.cars[j]; // whole list down one when
} // a duplicate is found,
// overwriting it.
i--; // sets the index back to recheck the shifted list.
this.noOfCars--; // You removed one duplicate by overwriting it
}
}
响应 @Boris The Spiders 评论,您可以通过消除内部 for 循环来降低此算法的复杂性。我建议通过跟踪最后一个有效位置并将其用于更新来做到这一点。
int writeIndex = 0;
for (int readIndex = 0; readIndex < this.cars.length; readIndex++) {
if (this.cars[readIndex] != null && this.cars[readIndex].getCarNum() == CarNum) {
// pass on this because nextIndex should track only the valid cars.
} else {
this.cars[writeIndex++] = this.cars[readIndex];
}
if (writeIndex < readIndex) {
this.cars[i] = null;
}
}
这个想法是您保留一个用于读取的索引 (i) 和一个用于写入的索引writeIndex。如果您的readIndex 领先于您的writeIndex(这意味着您找到了重复),您应该在阅读后将其清除,如果您将转移到之前的writeIndex。
编辑在回答您的问题时,您应该格外小心noOfCars 的计算方式,因为这可能是您的Exception 的来源,而是尝试更可靠的索引通过使用数组中的内在 length 属性的方法:
public String toString() {
String output = "";
for (int i = 0; i < this.cars.length; i++) {
if (this.cars[i] != null) {
output += "" + this.cars[i].toString() + "\n";
} else {
// condition that the i-th car is null
output += "null\n"; // one possible approach
// you could also do nothing and your toString would output just the non-null cars
}
}
return output;
}
为了可靠性,以效率为代价,您可以实现count() 方法来仔细检查您的跟踪。也许作为一个临时检查,直到你确定它工作正常。
public int getNumCars() {
int c = 0;
for (int i = 0; i < this.cars.length; i++) {
if (this.cars[i] != null) {
c++;
}
}
return c;
}