Java对象等于方法不起作用 [英] Java object equals method not work

查看:87
本文介绍了Java对象等于方法不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码有问题,equals方法无效,我尝试了 == .equals()但它不起作用。

I have trouble with my code, the equals method is not working, I have try both == and .equals() but it's not working.

这是main方法的代码:

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");

程序在屏幕上打印False。

The program is printing "False" in the screen.

这是我的卡类:

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;
    }
}

我该怎么办?

推荐答案

在您的情况下:

正确: if(x.equals(y))

错误: 如果(x == y)

如果等于 API不起作用,那么你已经在你的课程中覆盖了它,并且你已经错误地实现了它。

If the equals API is not working, then you've overridden it in your Card class, and you've implemented it wrong.

如果你没有' t覆盖它,然后这样做:

If you haven't overridden it, well then do it:

public class Card 
{
    ...

    @Override
    public boolean equals(final Object obj)
    {
        if ( obj == null || obj == this || !(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;
    }

}

这篇关于Java对象等于方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆