为什么在Java中,函数”equals”返回错误?

huangapple go评论67阅读模式
英文:

Why does function equals return error in Java

问题

我在Java中有一个名为Objekt的类,在该类中,我编写了一个函数来检查来自其他类的对象的对象序列号,但我一直收到.equals错误。我想知道这是不是因为我编写了一个字符串函数,而序列号(Evidenca)是整数,还是我写错了什么。所以欢迎任何想法。

boolean obstaja = false;
for (PoslovniProstor pp : this.PoslovniProstori) {
    if (pp.getEvidenca().equals(poslovniProstor.getEvidenca())) {
        obstaja = true;
        break;
    }
}

注意,上面代码中的.equals会显示为红色。请注意,我从中获取对象的类是PoslovniProstor,我在这个类Objekt中创建了一个名为PoslovniProstori的ArrayList。

public ArrayList<PoslovniProstor> getPoslovniProstori() {
    return this.PoslovniProstori;
}

所以,是的,欢迎任何帮助。 为什么在Java中,函数”equals”返回错误?

英文:

I have a class Objekt in java in that class I wrote a function to check objects the serial number of objects from other classes and I keep getting .equals error. I was wondering is it because I wrote String function and the serial number(Evidenca) is int or I wrote something wrong. So any ideas are welcome.

boolean obstaja = false;
    for(PoslovniProstor pp : this.PoslovniProstori)
    {
        if(pp.getEvidenca().equals(poslovniProstor.getEvidenca()))
        {
            obstaja = true;
            break;
        }
    }

This colors .equals in red bare in mind that the class I am taking an object from is PoslovniProstor and I created an ArrayList in this class Objekt and is called PoslovniProstori

public ArrayList&lt;PoslovniProstor&gt; getPoslovniProstori(){
    return this.PoslovniProstori;
}

So yea any help is welcome. 为什么在Java中,函数”equals”返回错误?

答案1

得分: 0

由于 int 是一种原始类型,必须使用 == 运算符进行比较,而不是使用 .equals() 方法。

英文:

As int is a primitive type, it has to be compared using == rather than .equals().

答案2

得分: 0

equals 方法和 == 运算符具有不同的用途。简而言之,equals 用于检查值的相等性,而 == 用于检查引用是否相同。
在您的情况下,由于您已经提到 Evidenca 是整数类型,所以要比较一个整数与另一个整数,请使用 == 运算符。

要了解更多详情,您可以查看这个讨论串 How do I compare strings in Java?

英文:

equals method and == operator have separate use cases. In short, equals is used to check for equality of value whether == is used to check for same reference.
In your case, as you have said Evidenca is int, then, to compare one int to another int use == operator.

For more details, you can check this thread How do I compare strings in Java?

huangapple
  • 本文由 发表于 2020年4月10日 17:56:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/61137872.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定