gpt4 book ai didi

java - ArrayList 和 List 的区别

转载 作者:行者123 更新时间:2023-11-29 10:06:54 24 4
gpt4 key购买 nike

您好,我正在尝试从列表中列出项目,并在每次迭代时打印 5 个。在下面的代码中,它每次都打印相同的项目

for(int i=0;i<4;i++)
{
List<Card> l=a.subList(a.size()-5, a.size());
System.out.println(l);

}

但是这里它打印不同的项目,就好像每次都从列表中删除 5

 for(int i=0;i<4;i++){
int deckSize = a.size();
List<Card> handView = a.subList(deckSize-5, deckSize);
ArrayList<Card> hand = new ArrayList<Card>(handView);
handView.clear();
System.out.println(hand);
}

上面两个代码片段有什么区别

最佳答案

您应该阅读 API for List .

The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.

因此在每种情况下,您创建的列表都不是原始列表中元素的新副本,而只是原始列表的 View 。在第二个示例中,您在新列表上调用 clear,这实际上是清除原始列表中的那些元素,因此您看到的是这种行为。

关于java - ArrayList 和 List 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5337589/

24 4 0