java - .get 如何与 ArrayList 一起使用,该索引是否会变空?

标签 java arraylist imageview vbox hbox

我正在编写一个具有 ImageViewArraylist 的程序。我正在使用 .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#get()

如果您想获取删除某个位置的元素,请使用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).

ArrayList#remove()

或者,如果您想弹出元素(获取并删除第一个/最后一个元素),请使用QueueStack

[编辑]

<小时/>

关于您的问题,根据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/

相关文章:

javascript - 在点击上传 javascript/jquery 之前显示图像

java - 如何将图像流式传输到 Amazon S3

c# - Azure 队列读/写限制

java - notifyDataSetChanged 不适用于 arraylist 数据类型

java - 如何正确 append 到 JTextPane

android - 图像不在 imageView android 中拉伸(stretch)

java - 为什么ArrayList、HashMap等类没有同步?

java - java中使用递归求数组中正元素的总和

java - 在java中生成List字符串的组合

ios - 在 ImageView 中旋转图像并保存到服务器