当前位置:  开发笔记 > 编程语言 > 正文

Java错误或功能?

如何解决《Java错误或功能?》经验,为你挑选了1个好方法。

好的,这是代码,然后讨论如下:

public class FlatArrayList {

    private static ArrayList probModel = new ArrayList();

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int [] currentRow = new int[10];

        int counter = 0;

        while (true) {

          for (int i = 0; i < 10; i++) {
            currentRow[i] = probModel.size();
          }

          TestWrapperObject currentWO = new TestWrapperObject(currentRow);

          probModel.add(counter, currentWO);

          TestWrapperObject testWO = probModel.get(counter);
          // System.out.println(testWO);

          counter++;

          if (probModel.size() == 10) break;

       }

       // Output the whole ArrayList    
       for (TestWrapperObject wo:probModel) {
         int [] currentTestRow = wo.getCurrentRow();
       } 
    }
}

public class TestWrapperObject {

    private int [] currentRow;

    public void setCurrentRow(int [] currentRow) {
        this.currentRow = currentRow;
    }

    public int [] getCurrentRow() {
        return this.currentRow;
    }

    public TestWrapperObject(int [] currentRow) {
        this.currentRow = currentRow;
    }

}

上面的代码应该做什么?我想要做的是加载一个数组作为一些包装器对象的成员(在我们的例子中是TestWrapperObject).当我离开循环时,probModel ArrayList具有它应该具有的元素数量,但是所有元素都具有相同的最后一个元素的值(大小为10的数组,每个项目等于9).循环中不是这种情况.如果使用原始int值执行相同的"实验",一切正常.我自己错过了关于数组作为对象成员的东西吗?或者我刚刚遇到Java错误?我使用的是Java 6.



1> Greg Hewgill..:

您只是创建一个currentRow数组实例.在行循环中移动它,它应该表现得更像你期望的.

具体来说,赋值in setCurrentRow不会创建对象的副本,而只会分配引用.因此,包装器对象的每个副本都将保存对同一int[]数组的引用.更改该数组中的值将使所有其他包装器对象的值看起来更改,这些包装器对象包含对该数组的同一实例的引用.

推荐阅读
手机用户2502851955
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有