UGStu[] a = new UGStu[stu.size()];
    stu.toArray(a); // stu is an arraylist
    a[14].setGrade(10000);
 // stu.set(10,new UGStu("jianren","366","noman",11111,3333));
    for (int count = 0;count < a.length;count ++)
    {
     System.out.println(((UGStu)(stu.get(count))).toString());
    System.out.println(((UGStu)(a[count])).toString());
    }
请问为什么上面通过 toArray 函数后 修改a【14】后 循环部分  输出相同
而通过 arraylist修改 (注释部分) 输出的内容却不相同呢 ??
麻烦 热心人帮忙解答 谢谢了~~~ 

解决方案 »

  1.   

    注释部分 中的意思是替换原下标为10的对象为新的UGStu对象。
    a[14].setGrade(10000);  修改下标为14的对象的grade值为10000
      

  2.   

    本人愿意为 toArray 方法只是把ArrayList 的内容拷贝一份给 数组 ,按理说修改 ArrayList 或者数组都不能够影响到对方,但是本人实验后发现通过数组来修改数据后,打印 ArrayList 中的相应内容也修改了 ,而通过修改 ArrayList 中对象的数据 ,保存在数组中的数据并没有改变。比较诡异
      

  3.   


    UGStu[] a = new UGStu[stu.size()]; 
        stu.toArray(a); // stu is an arraylist 
    这段代码执行过后,数组a和List stu 中保存的引用(你放进去的对象)都执行java堆中同一个对象。当你a[14].setGrade(10000); 时,
    其实是取出这个引用,然后修改了它的属性,那么list stu里对象的那个引用所指向的那个对象的属性也改变,
    因为他们本身就是同一个对象。楼主不妨这样改下一下你通过list 来修改属性的方法:
        UGStu[] a = new UGStu[stu.size()]; 
        stu.toArray(a); // stu is an arraylist 
        //a[14].setGrade(10000); 
       ((UGStu)stu.get(10)).setGrade(10000);
    // stu.set(10,new UGStu("jianren","366","noman",11111,3333)); 
        for (int count = 0;count < a.length;count ++) 
        { 
        System.out.println(((UGStu)(stu.get(count))).toString()); 
      System.out.println(((UGStu)(a[count])).toString()); 
        } 看看输出的结果。
      

  4.   

    谢谢你帮忙
    实验证明二者可能是共享堆里面的对象,但是奇怪的是我用// stu.set(10,new UGStu("jianren","366","noman",11111,3333));
    把 ARRAYLIST 里的那个对象替换以后 ,通过 System.out.println(((UGStu)(a[count])).toString()); 输出的居然是替换以前的对象的内容。不明白是为什么 ?
      

  5.   


    stu是Map类型的集合, 那么以键值对的形式保存的。
    所以你使用stu.get(count)方法来通过键取值,“count”是键。
    键和值不一定一样,键还不可以重复,值可以重复。
    你这里的对应关系可能如下:
    一、Map stu = new HashMap();
    String key = "1";
    String value = "3";
    stu.put(key, value); // 保存键值对
    key = "2";
    value = "1";
    stu.put(key, value);
    key = "3";
    value = "2";
    stu.put(key, value);二、Map stu = new HashMap();
    String key = "1";
    String value = "1";
    stu.put(key, value); // 保存键值对
    key = "2";
    value = "2";
    stu.put(key, value);
    key = "3";
    value = "3";
    stu.put(key, value);情况一的结果就如你现在这种情况,结果不同。
    情况二侥幸结果相同。
      

  6.   

    因为你用stu.set(10,new UGStu("jianren","366","noman",11111,3333));替换了list中的对象引用的时候,
    其实相当于你把List的index是10位置上的对象引用都替换到了。
    也就是说,你把那个原来的引用删除掉,然后加入了一个新的对象引用,这个对象就是通过new UGStu("jianren","366","noman",11111,3333)创造出来的。而你的数组里的a里面的所有的对象引用并没有变,
    所以输出的还是原来的。也就是说,你通过执行过stu.set(10,new UGStu("jianren","366","noman",11111,3333)); 之后,a和stu中的引用已经不全相同了。
    stu中的一个被替换了。