CopiesList.addAll method throws UnsupportedOperationException

后端 未结 2 1086
孤街浪徒
孤街浪徒 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:06

    Collections.nCopies returns an immutable List, so you can't add anything to it:

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

    It returns an immutable List since it only contains a single reference of the element you pass to its constructor:

    The newly allocated data object is tiny (it contains a single reference to the data object).

    This is done for the benefit of performance and storage requirements - Collections.nCopies(10, "Hi") and Collections.nCopies(10000000, "Hi") occupy the same amount of space.

    Therefore it would be very difficult to implement it as a mutable List. How would you set, for example, the 10000'th element to some new value if there's no storage allocated for that element?

    If you need a mutable List that contains copies of the same object, you have to pass the immutable List to some mutable List constructor:

    List mutable = new ArrayList<>(Collections.nCopies(10, "Hi"));
    

提交回复
热议问题