I have trouble with my code, the equals method is not working, I have try both == and .equals() but it's not working.
This is the code for main method:
x= new Card('♠',"number","3",5,Color.BLACK);
y= new Card('♠',"number","3",5,Color.BLACK);
if(x.equals(y)) System.out.println("True"); else System.out.println("False");
The program is printing "False" in the screen.
this is my Card class :
package core;
import java.awt.Color;
public class Card {
private char symbol;
private String type,value;
private int score;
private Color warna;
public Card(char symbol, String type, String value,int score,Color warna)
{
this.setSymbol(symbol);
this.setValue(value);
this.setType(type);
this.setScore(score);
this.warna = warna;
}
public char getSymbol() {
return symbol;
}
public void setSymbol(char symbol) {
this.symbol = symbol;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public Color getWarna() {
return warna;
}
public void setWarna(Color warna) {
this.warna = warna;
}
}
What should I do?
In your case:
Right: if ( x.equals(y) )
Wrong: if ( x == y )
If the equals API is not working, then you've overridden it in your Card class, and you've implemented it wrong.
If you haven't overridden it, well then do it:
public class Card
{
...
@Override
public boolean equals(final Object obj)
{
if (obj == this)
return true;
if (obj == null || !(obj instanceof Card))
return false;
Card otherCard = (Card) obj;
if (otherCard.score != this.score) return false;
if (otherCard.symbol != this.symbol) return false;
if (!otherCard.warna.equals(this.warna)) return false;
if (!otherCard.type.equals(this.type)) return false;
if (!otherCard.value.equals(this.value)) return false;
return true;
}
}
This is not using the equals() method, but is testing reference equality of the 2 instances:
if(x==y)
You need to call the equals() method if you want to use it.
UPDATE:
The equals() test is not working because you have not overridden the default Object.equals() method, which only tests reference equality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With