0

I'm writing a program that has an ImageView'sArraylist. I am using the .get() to take a dice imageview out from one arraylist and I add it to another Arraylist that is going to show all the dice that get chosen. I'm confused because does using the .get() remove it from the original 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));

In my code above, the diceingame ArrayList already has 6 image view dice added to it. I randomly choose one and add it to my rolledhand array list 5 times. When I try to output the same index of rolledhand, only one shows up on my scene, not two of the same.


I'm not trying to remove it. I'm just asking because for some reason my program won't show both dice if they are from the same position in diceingame.

Cà phê đen
  • 1,883
  • 2
  • 21
  • 20

1 Answers1

1

ArrayList#get() does not remove anything. It just gets the element:

public E get(int index)

Returns the element at the specified position in this list.

ArrayList#get()

If you want to get and remove the element at a position, use ArrayList#remove() instead:

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()

Or if you want to pop out the element (get and remove the first/last element), use Queue or Stack.

[Edit]


About your question that only one element appears on the view, according to the Node document (which ImageView is inherited from):

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.

Cà phê đen
  • 1,883
  • 2
  • 21
  • 20