两张牌 c1 和 c4 似乎是相等的……但它们不是为什么。我希望它们相等,以便集合中只允许其中一个。:|
import java.util.*;
class Card2
{
private int value;
private String type;
public Card2(int v,String t)
{
value=v;
type=t;
}
public int getValue()
{
return value;
}
public String getType()
{
return type;
}
public String toString()
{
return(type+" "+value);
}
public boolean equals(Object oo)
{
if(!(oo instanceof Card))
return false;
Card cc=(Card) oo;
if(this.getValue()==cc.getValue() && this.getType().equals(cc.getType()))
return true;
else
return false;
}
public int hashCode()
{
return value;
}
public static void main(String args[])
{
HashSet<Card> deck=new HashSet<Card>();
Card c1=new Card(5,"Spade");
Card c2=new Card(10,"Hearts");
Card c3=c2; //Equal Ref card entity
Card c4=new Card(5,"Spade");
System.out.println(c1.equals(c4));
deck.add(c1);
deck.add(c2);
deck.add(c4);
deck.add(c3);
for(Card cc:deck)
System.out.println(cc);
}
}