编程语言
首页 > 编程语言> > java – ArrayList.add(idx,element)损坏了数组的其他元素

java – ArrayList.add(idx,element)损坏了数组的其他元素

作者:互联网

我正在运行一个程序:

>创建一个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]
- - - - - - - -

在最后一个输出块中,当我从未添加两次相同的小时时,有7小时5次.

我问:为什么(你可以看到)添加这个数组顶部的元素会导致after元素被破坏?

我的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)

您可以提供的任何帮助都非常感谢.

解决方法:

您将多次添加相同的实例到List:

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实例,然后再将其添加到List中:

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

标签:corruption,java,arrays,arraylist
来源: https://codeday.me/bug/20190724/1527479.html