黑马程序员技术交流社区

标题: 谁能帮我看下下面的问题? [打印本页]

作者: AlanHand    时间: 2014-9-15 13:01
标题: 谁能帮我看下下面的问题?
  1. public class FillingList {
  2.         public static void main(String[] args) {

  3.                 List<Integer> list = new ArrayList<Integer>(Collections.nCopies(4,
  4.                                 new Integer(2)));

  5.                 System.out.println(list);
  6.                 Collections.fill(list, new Integer(1));
  7.                 System.out.println(list);
  8.                

  9. //                List<Integer> list=new ArrayList<Integer>();
  10. //                list=Collections.nCopies(4, new Integer(1));
  11. //                System.out.println(list);
  12. //                Collections.fill(list, new Integer(1));
  13. //                System.out.println(list);
  14.         }
  15. }
复制代码


没有注释的代码 运行正常,注释的代码有异常,请详解
作者: 沙拉很好吃    时间: 2014-9-15 13:06
把异常贴出来,看看
作者: fantacyleo    时间: 2014-9-15 14:11
Collections.nCopies(4, new Integer(1))返回一个List,这个List没说一定就是ArrayList,你用ArrayList去接收,抛异常很正常
作者: Fightin黑马    时间: 2014-9-15 17:48
Collections.fill(list, new Integer(1))这一句报错原因是Collections.nCopies(4, new Integer(1))返回的是一个不可变的集合,你试图去改变里面的元素,虽然值是一样的,但是是new出来的 在内存中的位置也不一样.Collections API nCopies这个方法返回由指定对象的 n 个副本组成的不可变列表。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2