我正在编写一个具有 ImageView
的 Arraylist
的程序。我正在使用 .get()
从一个 arraylist
中取出一个骰子 imageview
,然后将其添加到另一个 Arraylist
将显示所有被选中的骰子。我很困惑,因为使用 .get()
是否会将其从原始 Arraylist
中删除?
ArrayList<ImageView> rolledhand=new ArrayList<>(5);
Random rand = new Random();
for(int i=0;i<5;i++)
{
int randomNum = rand.nextInt(6);
rolledhand.add(diceingame.get(randomNum));
}
VBox diceRolled1=new VBox(rolledhand.get(0));
VBox diceRolled2=new VBox(rolledhand.get(0));
在我上面的代码中,diceingame
ArrayList
已经添加了 6 个 ImageView 骰子。我随机选择一个并将其添加到我的 rolledhand
数组列表中 5 次。当我尝试输出相同索引的 rolledhand
时,场景中只出现一个,而不是两个相同的。
我并不是想删除它。我只是这么问,因为出于某种原因,如果两个骰子来自 diceingame
中的同一位置,我的程序将不会显示它们。
最佳答案
ArrayList#get()
不会删除任何内容。它只是获取
元素:
public E get(int index)
Returns the element at the specified position in this list.
如果您想获取
并删除
某个位置的元素,请使用ArrayList#remove()
:
public E remove(int index)
Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).
或者,如果您想弹出元素(获取并删除第一个/最后一个元素),请使用Queue
或Stack
。
[编辑]
<小时/>关于您的问题,根据Node
, View 上只出现一个元素文档(ImageView
继承自):
A node may occur at most once anywhere in the scene graph. Specifically, a node must appear no more than once in all of the following: as the root node of a Scene, the children ObservableList of a Parent, or as the clip of a Node.
...
If a program adds a child node to a Parent (including Group, Region, etc) and that node is already a child of a different Parent or the root of a Scene, the node is automatically (and silently) removed from its former parent.
关于java - .get 如何与 ArrayList 一起使用,该索引是否会变空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58618235/