CopiesList.addAll method throws UnsupportedOperationException

后端 未结 2 1118
孤街浪徒
孤街浪徒 2021-01-14 03:39
List hi = Collections.nCopies(10, \"Hi\");
List are = Collections.nCopies(10, \"Are\");

hi.addAll(are);

hi.forEach(System.out::println)         


        
2条回答
  •  醉酒成梦
    2021-01-14 04:24

    As the JavaDoc says, the returned list is immutable, which means you can't modify it:

    [nCopies] Returns an immutable list consisting of n copies of the specified object.

    Maybe you didn't get the "in combination with the List.addAll" part. You must have a non-immutable list in which you can add all your elements:

    List modifiableList = new ArrayList();
    
    List hi = Collections.nCopies(10, "Hi");
    List are = Collections.nCopies(10, "Are");
    
    modifiableList.addAll(are);
    modifiableList.addAll(hi);
    
    modifiableList.forEach(System.out::println);
    

提交回复
热议问题