Java比较两个相同的对象会得出false [英] Java Comparing two identical objects gives false
问题描述
我有一个自定义类,称为Card
I have a custom class called Card
public class Card implements Serializable, Comparable<Card>{
private static final long serialVersionUID = 100L;
private Rank rank;
private Suit suit;
public Card(Rank rank, Suit suit){
this.rank = rank;
this.suit = suit;
}
public enum Rank{
TWO(2), THREE(3), FOUR(4), FIVE(5), SIX(6), SEVEN(7), EIGHT(8), NINE(9), TEN(10), JACK(10), QUEEN(10), KING(10), ACE(11);
private final int value;
Rank(int value){
this.value = value;
}
}
public enum Suit{
CLUBS, DIAMONDS, HEARTS, SPADES;
public static Suit getSuit(){
Random rand = new Random();
return values()[rand.nextInt(values().length)];
}
}
要检查它们是否相同这样做:
To check if they're the same I'm doing this:
Card smth = new Card(Card.Rank.ACE,Card.Suit.CLUBS);
Card smth1 = new Card(Card.Rank.ACE,Card.Suit.CLUBS);
System.out.println(smth.equals(smth1));
但它总是给我 false
和我不知道为什么会这样,我也尝试过将它们放在 ArrayList
中,并使用 contains()
检查,但是
but its always giving me false
and I have no idea why is that, I've also tried putting them in an ArrayList
and checking with contains()
but the output is the same.
推荐答案
equals()
根据对象在内存中的地址比较对象。意味着不同的对象将被认为是不平等的。
The default implementation of equals()
compares objects by their adress in memory. Meaning different objects will be considered unequal. This is called comparing by identity.
要按值比较对象时,必须创建自己的equals方法,该方法比较等级
和西装
。这可能很困难,因为您还必须验证两个对象都不为空,并且必须验证对象类型,才能从 Object
安全地对其进行强制转换。这称为按值比较。
When you want to compare objects by value, you have to create you own equals method, which compares the values of rank
and suit
. This can be difficult because you also have to verify neither of the objects is null and very the object type to be able to safely cast it from Object
. This is called comparing by value.
一个有用的技巧是使用Eclipse生成equals函数。
A useful tip for this is to generate the equals function using Eclipse.
这篇关于Java比较两个相同的对象会得出false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!