我正在运行一个程序:
- 创建一个
ArrayList
- 在这个数组的顶部添加一些元素
- 创建一个将减少的“基础”元素
- 然后使用 for 循环减少基元素并将其添加到数组的顶部(索引 0)
- 没想到我得到的输出是可怕的
请不要对一些意大利语词感到难过:
“ora”表示小时,所以
Ora hour = new Ora(6,34) //--> 6:34
"decrementaMinuti"从小时开始减少分钟数
这是完整的代码:
public static void main(String[] args) {
ArrayList<Ora> hours = new ArrayList<>();
hours.add(0, new Ora(01,00));
hours.add(0, new Ora(00,00));
Ora base = hours.get(0);
System.out.println("Base: " + base + "\n");
for (int i = 0; i < 4; i++) {
System.out.println("First: " + base);
// decreasing 60 minutes from hour
base.decrementaMinuti(60);
System.out.println("After: " + base);
hours.add(0, base);
System.out.println("In Array: " + hours.get(0));
System.out.println("[hours]");
for (int j = 0; j < hours.size(); j++) {
System.out.println("[" + hours.get(j) + "]");
}
System.out.println("- - - - - - - -\n");
}
}
这是我得到的输出:
Base: 11:00
First: 11:00
After: 10:00
In Array: 10:00
[hours]
[10:00]
[10:00]
[12:00]
- - - - - - - -
First: 10:00
After: 09:00
In Array: 09:00
[hours]
[09:00]
[09:00]
[09:00]
[12:00]
- - - - - - - -
First: 09:00
After: 08:00
In Array: 08:00
[hours]
[08:00]
[08:00]
[08:00]
[08:00]
[12:00]
- - - - - - - -
First: 08:00
After: 07:00
In Array: 07:00
[hours]
[07:00]
[07:00]
[07:00]
[07:00]
[07:00]
[12:00]
- - - - - - - -
在最后一个输出 block 中,有 5 次 7:00
时间,而我从来没有两次添加相同的时间。
我在问:为什么(如您所见)在这个数组的顶部添加一个元素会导致后面的元素也被破坏?
我的java版本:
java version "1.7.0_79"
Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.79-b02, mixed mode)
非常感谢您提供的任何帮助。
最佳答案
您将同一实例多次添加到列表中:
Ora base = hours.get(0); // this is the instance added multiple times
System.out.println("Base: " + base + "\n");
for (int i = 0; i < 4; i++) {
System.out.println("First: " + base);
// decreasing 60 minutes from hour
base.decrementaMinuti(60);
System.out.println("After: " + base);
hours.add(0, base); // here you add the same instance multiple times
在将它添加到列表之前,您必须创建一个新的 Ora
实例:
Ora base = hours.get(0);
System.out.println("Base: " + base + "\n");
for (int i = 0; i < 4; i++) {
System.out.println("First: " + base);
Ora newOra = new Ora (...); // consider having a copy constructor that
// would accept base and copy its data
// add code to update newOra to contain the same data as base
// decreasing 60 minutes from hour
newOra.decrementaMinuti(60);
System.out.println("After: " + newOra);
hours.add(0, newOra); // add the new instance
关于java - ArrayList.add(idx,element) 损坏数组的其他元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31180995/