我尝试创建一个 8 元素列表 [0,0,0,0,0,0,0,0],然后使用 .set 方法更改给定索引的值。但是该代码引发了异常。
import java.util.*;
public class HQ {
public static void main(String[] arg)
{
List<Integer> quantity= Collections.nCopies(8, 0);
quantity.set(0,1);
}
}
我认为它将把数量的第一个元素更改为 1,并将其余元素保留为 0。
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.set(AbstractList.java:132)
at HQ.main(HQ.java:10)
最佳答案
Collections.nCopies将返回不可变列表,因此您无法修改它
Returns an immutable list consisting of n copies of the specified object. The newly allocated data object is tiny (it contains a single reference to the data object). This method is useful in combination with the List.addAll method to grow lists. The returned list is serializable.
您可以使用stream
创建具有n个副本的可变列表
List<Integer> ints = IntStream.range(0, 7).map(i -> 0).boxed().collect(Collectors.toList());
或者只是将不可变列表转换为可变列表
List<Integer> quantity1= Collections.nCopies(8, 0);
List<Integer> quantity = new ArrayList<Integer>(quantity1);
关于java - 在 List<Integer> 上使用 set 方法会导致不支持的操作异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57000947/