两个比较运算符 java_关于java:使用.equals()和==运算符比较两个对象

我用一个String字段构造了一个类。 然后,我创建了两个对象,还必须使用==运算符和.equals()比较它们。 这是我所做的:

public class MyClass {

String a;

public MyClass(String ab) {

a = ab;

}

public boolean equals(Object object2) {

if(a == object2) {

return true;

}

else return false;

}

public boolean equals2(Object object2) {

if(a.equals(object2)) {

return true;

}

else return false;

}

public static void main(String[] args) {

MyClass object1 = new MyClass("test");

MyClass object2 = new MyClass("test");

object1.equals(object2);

System.out.println(object1.equals(object2));

object1.equals2(object2);

System.out.println(object1.equals2(object2));

}

}

编译后显示两次错误。 如果两个对象具有相同的字段-"测试",为什么会为假?

顺便说一句,查看equals和equals2:每当您使用if(a) { return true; } else { return false; }形式的内容时,您可能应该只写return a。

@yshavit您的意思是,从boolean更改为String?

不,您的代码正在询问布尔值是否为true,然后返回true,否则返回false。 因此,例如,if(a.equals(object2)) { return true; } else return false可能只是return a.equals(object2)。

如何比较Java中的字符串的可能重复项?

==比较对象引用,它检查两个操作数是否指向相同的对象(不是等效的对象,是相同的对象)。

如果要比较字符串(以查看它们是否包含相同的字符),则需要使用equals比较字符串。

在您的情况下,如果字符串匹配,则MyClass的两个实例确实被视为相等,则:

public boolean equals(Object object2) {

return object2 instanceof MyClass && a.equals(((MyClass)object2).a);

}

...但是通常,如果您要定义一个类,那么等效性要比单个字段的等效性大(本例中为a)。

旁注:如果覆盖equals,几乎总是需要覆盖hashCode。如equals JavaDoc中所述:

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

你应该覆盖等于

public boolean equals (Object obj)

{

if (this==obj) return true;

if (this == null) return false;

if (this.getClass() != obj.getClass()) return false;

// Class name is Employ & have lastname

Employe emp = (Employee) obj ;

return this.lastname.equals(emp.getlastname());

}

可以说这是最好的答案,但是对于非原始类型,您可能要使用this.equals(obj)而不是(this == null)

我认为if (this == null)情况是不必要的。调用nullObject.equals(whatever)将抛出空指针异常,因此我们可以安全地假定this在我们可能编写的任何Java方法中都不为null。

当this具有lastname null并且不满足先前条件时,此操作将失败。

看起来equals2只是在调用equals,因此它将给出相同的结果。

覆盖函数equals()是错误的。

对象" a"是String类的实例,而" object2"是MyClass类的实例。它们是不同的类,因此答案是"假"。

您的equals2()方法总是返回与equals()相同的结果!

您的代码加上我的评论:

public boolean equals2(Object object2) {  // equals2 method

if(a.equals(object2)) { // if equals() method returns true

return true; // return true

}

else return false; // if equals() method returns false, also return false

}

FFS,仅return a.equals(object2);

比较2个对象的最好方法是将它们转换为json字符串并比较这些字符串,这是处理复杂的嵌套对象,字段和/或包含数组的对象时最简单的解决方案。

样品:

import com.google.gson.Gson;

Object a = // ...;

Object b = //...;

String objectString1 = new Gson().toJson(a);

String objectString2 = new Gson().toJson(b);

if(objectString1.equals(objectString2)){

//do this

}

我想这样称呼:过度杀伤力。

@Rolfツ为什么您认为这太过分了? Ive寻找了解决此问题的方法,这是迄今为止Ive找到的最简单的解决方案。欢迎任何更好的建议。

因为使用Java,您无需先创建Gson对象然后调用toJson就可以比较对象。创建Gson对象并调用将实际对象转换为平面String(toJson)所需的逻辑是不必要的开销。您可以比较对象而无需先将对象转换为Json字符串(这也更快)。

语句a == object2和a.equals(object2)都将始终返回false,因为a是string,而object2是MyClass的实例

您的实现必须喜欢:

public boolean equals2(Object object2) {

if(a.equals(object2.a)) {

return true;

}

else return false;

}

通过这种实现,您两种方法都可以使用。

您的类可能会实现Comparable接口以实现相同的功能。您的类应实现在接口中声明的compareTo()方法。

public class MyClass implements Comparable{

String a;

public MyClass(String ab){

a = ab;

}

// returns an int not a boolean

public int compareTo(MyClass someMyClass){

/* The String class implements a compareTo method, returning a 0

if the two strings are identical, instead of a boolean.

Since 'a' is a string, it has the compareTo method which we call

in MyClass's compareTo method.

*/

return this.a.compareTo(someMyClass.a);

}

public static void main(String[] args){

MyClass object1 = new MyClass("test");

MyClass object2 = new MyClass("test");

if(object1.compareTo(object2) == 0){

System.out.println("true");

}

else{

System.out.println("false");

}

}

}

仅当两个引用指向内存中的同一对象时," =="运算符才返回true。另一方面,equals()方法根据对象的内容返回true。

例:

String personalLoan = new String("cheap personal loans");

String homeLoan = new String("cheap personal loans");

//since two strings are different object result should be false

boolean result = personalLoan == homeLoan;

System.out.println("Comparing two strings with == operator:" + result);

//since strings contains same content , equals() should return true

result = personalLoan.equals(homeLoan);

System.out.println("Comparing two Strings with same content using equals method:" + result);

homeLoan = personalLoan;

//since both homeLoan and personalLoan reference variable are pointing to same object

//"==" should return true

result = (personalLoan == homeLoan);

System.out.println("Comparing two reference pointing to same String with == operator:" + result);

输出:

用==运算符比较两个字符串:false

使用equals方法比较两个具有相同内容的字符串:true

使用==运算符将指向相同String的两个引用进行比较:true

您还可以从以下链接获取更多详细信息:http://javarevisited.blogspot.in/2012/12/difference-between-equals-method-and-equality-operator-java.html?m=1

如果不需要自定义默认的toString()函数,则另一种方法是重写toString()方法,该方法返回所有要比较的属性。 然后比较两个对象的toString()输出。 我使用IntelliJ IDEA IDE生成了toString()方法,该方法在字符串中包含类名称。

public class Greeting {

private String greeting;

@Override

public boolean equals(Object obj) {

if (this == obj) return true;

return this.toString().equals(obj.toString());

}

@Override

public String toString() {

return"Greeting{" +

"greeting='" + greeting + '\'' +

'}';

}

}

object.equals的返回类型已经是布尔值。

无需将其包装在带有分支的方法中。因此,如果您想比较两个对象,只需将它们进行比较:

boolean b = objectA.equals(objectB);

b已经是对或错。

在这里,输出将为false,因为在第一个sopln语句中,您试图将Myclass类型的字符串类型变量与另一个MyClass类型进行比较,并且由于两者都是Object类型,并且您使用了" ==" oprerator将会检查保存实际内存而不是内存内部实际内容的参考变量值。

在第二个解决方案中,它也与您再次调用a.equals(object2)相同,其中a是object1内部的变量。让我知道你对此的发现。

欢迎来到stackoverflow bidyadhar。该问题的日期为2012年11月14日,已经得到了很好的答复(由OP批准)。您得到的是正确的,但没有添加有用的信息。我建议你在做任何事情之前先阅读规则

当使用==时,将比较对象的引用而不是实际对象。我们需要重写equals方法来比较Java对象。

C ++具有操作符重载的一些附加信息,而Java不提供操作符重载。

Java中的其他可能性还包括实现Compare接口。该接口定义了compareTo方法。

比较器接口也用于比较两个对象

考虑到您的答案没有增加将近2年前说过的话。

/** Comparing two or more variables. Here the two items are compared and it will return a boolean true or false.

*

* @return equals

*/

public boolean equals(Object item)

{

String emp1 = this.toString();

String emp2 = item.toString();

return emp1.equals(emp2);

}

@Override

//In case you have more than one variable.

public String toString()

{

return a + b;

}

// a and b represent the variables to display.

为您的答案添加解释,以帮助OP和未来的读者理解它。

在下面的代码中,您正在调用重写的方法.equals()。

public boolean equals2(Object object2){

if(a.equals(object2)){//在这里,您正在调用重写方法,这就是为什么您两次出错的原因。

返回true;

}

否则返回假;

}

不,a.equals是字符串方法,任何地方都不会覆盖它。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值