【问题标题】:Assign operator in JavaJava中的赋值运算符
【发布时间】:2014-04-17 14:58:26
【问题描述】:

我在 Java 中有 2 个 ArrayList:

mProductList = new ArrayList<ProductSample>();
mProductList2 = new ArrayList<ProductSample>();

mProductList = productSampleList;

mProductList2 = productSampleList;

mProductList2 .remove(3);

productSampleList 的大小为 5。 为什么在执行此段代码之后。 mProductList 的大小为 4?

我们有办法避免这种情况吗?我希望 mProductList 的大小与 productSampleList 相同。
谢谢!

【问题讨论】:

    标签: java assignment-operator


    【解决方案1】:

    试试这个:

    mProductList2 = new ArrayList<ProductSample>(productSampleList);
    

    目前,productSampleListmProductListmProductList2 都指向同一个对象,因此对其中一个的更改将反映在其他对象上。我的解决方案是简单地创建一个可以独立于原始列表进行修改的列表副本,但请记住:productSampleListmProductList 仍然指向同一个对象。

    【讨论】:

    • @VanDang 不,您没有,在mProductList2 = productSampleList; 行中,您将mProductList2 重新分配到了不同的列表。您必须掌握 Java 中对象引用的概念。
    • 我明白了!非常感谢您的帮助!我是Java新手,所以这个错误是不可避免的。再次感谢。
    【解决方案2】:

    所有 3 个 productSampleListmProductListmProductList2 都是对同一个 ArrayList 对象的引用,因此在其中任何一个上调用 .remove() 方法都会从底层单个 ArrayList 对象中删除该元素。

    如果您想为每个变量维护单独的 ArrayList 引用,则需要创建 3 个不同的 ArrayLists

    【讨论】:

      【解决方案3】:

      当您使用列表(或数组列表)时,size() 方法返回列表中元素的数量。列表不像数组,数组的大小是固定的。如果要固定大小,请使用数组。

      查看http://docs.oracle.com/javase/7/docs/api/java/util/List.html 以了解有关列表的更多信息。

      Here 很好区分数组和数组列表。

      【讨论】:

        【解决方案4】:

        你可以试试这个:-

            public class ArrayListTest {
        
            public static void main(String str[]){
                ArrayList productSampleList=new ArrayList();
                ArrayList mProductList=null;
                ArrayList mProductList2=null;
        
                productSampleList.add("Hi");
                productSampleList.add("Hi");
                productSampleList.add("Hi");
                productSampleList.add("Hi");
                productSampleList.add("Hi");
        
                System.out.println("Main productSampleList size..."+productSampleList.size());
                mProductList=new ArrayList(productSampleList);
                mProductList2=new ArrayList(productSampleList);
                System.out.println("mProductList size..."+mProductList.size());
                System.out.println("mProductList2 size..."+mProductList2.size());
                mProductList2.remove(1);
                System.out.println("mProductList size..."+mProductList.size());
                System.out.println("mProductList2 size..."+mProductList2.size());
        
            }
        }
        

        输出:-

        Main productSampleList size...5
        
        mProductList size...5
        
        mProductList2 size...5
        
        mProductList size...5
        
        mProductList2 size...4
        

        【讨论】:

          猜你喜欢
          • 2011-11-16
          • 2015-05-02
          • 2015-03-19
          • 1970-01-01
          • 2013-02-14
          • 2018-11-30
          • 1970-01-01
          • 2014-11-08
          • 1970-01-01
          相关资源
          最近更新 更多