英文:
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;
}
所以,是的,欢迎任何帮助。
英文:
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<PoslovniProstor> getPoslovniProstori(){
return this.PoslovniProstori;
}
So yea any help is welcome.
答案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?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论