【发布时间】:2013-12-04 21:28:36
【问题描述】:
我的代码有问题,equals 方法不起作用,我尝试了== 和.equals(),但它不起作用。
这是main方法的代码:
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");
程序在屏幕上打印“False”。
这是我的卡片类:
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;
}
}
我该怎么办?
【问题讨论】:
-
如果你的 equals 方法有问题,你应该在这里发布。
-
你是否覆盖了
Card中的equals方法? -
== 只是比较引用并查看它们是否指向同一个对象。 'Equals()' 应该比较对象,但是如果你创建一个新类型,你必须指定比较是如何工作的。
-
你没有在你的类中重写方法
equals。谷歌“如何覆盖equals()”. -
@Mukhlas1940 如果你想使用 equals() 来比较你的对象,你需要。
标签: java