A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© AlanHand 高级黑马   /  2014-9-15 13:01  /  845 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  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. }
复制代码


没有注释的代码 运行正常,注释的代码有异常,请详解

3 个回复

倒序浏览
把异常贴出来,看看
回复 使用道具 举报
Collections.nCopies(4, new Integer(1))返回一个List,这个List没说一定就是ArrayList,你用ArrayList去接收,抛异常很正常
回复 使用道具 举报
Collections.fill(list, new Integer(1))这一句报错原因是Collections.nCopies(4, new Integer(1))返回的是一个不可变的集合,你试图去改变里面的元素,虽然值是一样的,但是是new出来的 在内存中的位置也不一样.Collections API nCopies这个方法返回由指定对象的 n 个副本组成的不可变列表。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马