Andrej Paučo Andrej Paučo - 15 days ago 5
Java Question

Java arraylist all items are the same

Why are all the cards in the list the same ?
I tried

hand.add(i,card);

but output is still the same.

Main.java

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Main {

public static void main(String[] args) {
List<Card> hand = new ArrayList();
Card card = new Card((short) 7,"red");
int b = 0;
Random rn = new Random();
for (int i=0;i<7;i++){
card.setValue((short) (rn.nextInt((14 - 7) + 1) + 7));
b = rn.nextInt(4);
String[] colors = {"green","red","gold","brown"};
card.setColor(colors[b]);
System.out.println("Adding card to hand: " + card.getColor() + card.getValue() + " to: " +i);
hand.add(card);
}
System.out.println("Your cards: ");
for (Card k: hand) {
System.out.println(k.show());
}


}
}


Card.java

public class Card {
public short getValue() {
return value;
}

public void setValue(short value) {
this.value = value;
}

short value;

public String getColor() {
return color;
}

public void setColor(String farba) {
this.color = farba;
}

String color;

public Card(short value, String color) {
this.value = value;
this.color = color;
}

public String show(){
return color + value;
}
}


Output:

/usr/lib/jvm/java-1.8.0-openjdk-amd64/bin/java
Adding card to hand: red13 to: 0
Adding card to hand: green10 to: 1
Adding card to hand: gold8 to: 2
Adding card to hand: brown10 to: 3
Adding card to hand: gold10 to: 4
Adding card to hand: gold8 to: 5
Adding card to hand: gold7 to: 6
Your cards:
gold7
gold7
gold7
gold7
gold7
gold7
gold7


Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean nisl.Curabitur ac arcu ornare, aliquet eros eu, pretium massa.

Answer

You are using the same Card object for all items in the list, but you need different objects (each Card object holds it's own color and value), so you have to create the new Card inside the for loop as shown below:

    int b = 0;
    Random rn = new Random();
    for (int i=0;i<7;i++){

        b = rn.nextInt(4);
        String[] colors = {"green","red","gold","brown"};

        Card card = new Card((short) (rn.nextInt((14 - 7) + 1) + 7),colors[b]);

        System.out.println("Adding card to hand: " + 
             card.getColor() + card.getValue() + " to: " +i);

        hand.add(card);
    }
Comments