ArrayList duplicated/replaced objects
alright, this seems to be a pretty simple problem if you know what's going on here, i just for some reason can't figure out a way around it.. i'm just not familiar with the convention of how to avoid it really...
my issue is that i want to simulate a deck of cards but i'm having difficulty adding these objects without updating the ones already in the list. When ever I call new, what seems to happen is i always allocate the same object and just repeated add the same thing... how do i avoid this...
here's my code:
public class Card implements Comparable<Card>{
private static int number;
public enum Suit{hearts, spades, dimons, clubs};
private static Suit suit;
public Card (int rank, Suit suit){
number = rank;
Card.suit = suit;
}
int getRank(){return number;}
Suit getSuit(){return suit;}
public int compareTo(Card card){
if(number>card.getRank()){return 1;}
if(number<card.getRank()){return -1;}
else{return 0;}
}
public String toString(){
String val;
if(number == 1){val = "A";}
else if(number == 11){val = "J";}
else if(number == 12){val = "Q";}
else if(number == 13){val = "K";}
else{val = Integer.toString(number);}
return new String(val + " " + suit);
}
}
import java.util.ArrayList;
public class Deck {
private ArrayList<Card> deck;
public Deck()
{
deck = new ArrayList<Card>();
for ( Card.Suit suit : Card.Suit.values()){
for ( int rank = 1; rank <= 13;rank++ ){
deck.add(new Card(rank,suit));
}
}
}
public boolean print(){
for(Card c: deck){
System.out.println(c);
}
return false;
}
public static void main(String[] args){
new Deck().print();
}
}
the console prints K clubs 52 times which is obviously not the desire effect... what is wrong? What should I be doing instead?
Thanks.