比较对象永远不会返回true [英] Comparing objects never returns true

查看:141
本文介绍了比较对象永远不会返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试比较两个相同类型的对象(在方法中有),但我从未得到true返回。这是我的代码:

I'm trying to compare two objects of the same type (in method doesHave), but I've never got "true" returned. Here's my code:

private ArrayList<Osoba> osoba = new ArrayList<Osoba>();    

public boolean doesHave(Osoba o) {
        for (int i = 0; i < osoba.size(); i++) {
            if (pobierz(i).equals(o))
                return true;
        }
        return false;
    }

public Osoba pobierz(int index) {
            return osoba.get(index);
        }

'Osoba'类,如下所示:

The 'Osoba' class, looks like this:

public class Osoba {
    private String imie;
    private String nazwisko;

    public String toString() {
        return imie + " " + nazwisko;
    }

    public Osoba(String name, String surname) {
        imie = name;
        nazwisko = surname;
    }

    public String getImie() {
        return imie;
    }

    public String getNazwisko() {
        return nazwisko;
    }
}

主要代码:

Osoba osoby = new Osoba(name, surname);
if (kartoteka.doesHave(osoby) == Boolean.TRUE) {
            temp = odczyt.nextLine();
            if (temp.equals("y"))
                kartoteka.usun(osoby); //some method
            else
                ...
        }

无论我使用什么输入,这部分都不会发生。
'kartoteka'是我的包裹,当然我已导入。每个类都在单独的包中,但使用它们没有问题。我已经尝试谷歌搜索了很长一段时间,但没有什么帮助我,它似乎只是

No matter what input I'd use, this part never happens. 'kartoteka' is my package which of course I have imported. Each class is in separate package, but there is no problem with using them. I've tried googling it for quite some time, but nothing helped me, it just seems like

if (kartoteka.doesHave(osoby) == Boolean.TRUE)

从来都不是,但我不明白为什么。没有Boolean.TRUE的代码也不起作用。如果我能得到一些提示,我会感激不尽。很抱歉提出这样的问题,但我是java新手。

Is never true, but I have no idea why. Code without Boolean.TRUE doesn't work as well. If I could get some hints, I'd be thankful. Sorry for asking that kind of question, but I'm new in java.

推荐答案

想象一下你和你的妻子有双胞胎。

Imagine that you and your wife have twins.

他们是同一个人吗?不,他们不是。让我们称他们为双胞胎A和双胞胎B.他们是两个不同的情况,是的,他们看起来一样,但如果你说的是双胞胎A,你不是在谈论双胞胎B,反之亦然。关键是,它们不是EQUAL :),它在Java中是相同的。 Twin A只等于它自己,no1 else。

Are they the "same" person? No, they are not. Lets call them twin A and twin B. They are two different instances, yes, they look same, but if you are talking twin A, you are not talking about twin B and vice versa. The point is, they are not EQUAL :), it is same in Java. Twin A is equal only to itself, no1 else.

你必须创建自己的方法,它比较两个Osoba实例的所有属性。

You have to create your own method, which compares all properties of two instances of Osoba.

另一种选择是覆盖equals和hashCode方法,但在你的情况下这不是好方法。

The other option is to override the equals and hashCode methods, but it is not good approach in your case.

这篇关于比较对象永远不会返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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