equals(Object obj) 是 Object 类的方法。此方法用于比较给定的对象。建议重写 equals(Object obj) 方法以获得我们自己的对象相等条件。
用法
public boolean equals(Object obj)
参数
obj- 它是参考对象。
返回
如果此对象与 obj 参数相同,则返回 true,否则返回 false。
例子1
public class JavaObjectequalsExample1 {
static int a = 10, b=20;
int c;
// Constructor
JavaObjectequalsExample1()
{
System.out.println("Addition of 10 and 20:");
c=a+b;
System.out.println("Answer:"+c);
}
// Driver code
public static void main(String args[])
{
System.out.println("1st object created...");
JavaObjectequalsExample1 obj1 = new JavaObjectequalsExample1();
System.out.println("2nd object created...");
JavaObjectequalsExample1 obj2 = new JavaObjectequalsExample1();
System.out.println("Objects are equal:" + obj1.equals(obj2));
}
}
输出:
1st object created... Addition of 10 and 20: Answer:30 2nd object created... Addition of 10 and 20: Answer:30 Objects are equal:false
例子2
public class JavaObjectequalsExample2{
static int a = 10, b=20;
int c;
// Constructor
JavaObjectequalsExample2()
{
System.out.println("Addition of 10 and 20:");
c=a+b;
System.out.println("Answer:"+c);
}
JavaObjectequalsExample2(int x, int y)
{
System.out.println("Parameterized Constructors");
System.out.println("Addition " +x+ " and " +y);
c=x+y;
System.out.println("Answer:"+c);
}
// Driver code
public static void main(String args[])
{
System.out.println("1st object created...");
JavaObjectequalsExample2 obj1 = new JavaObjectequalsExample2();
System.out.println("2nd object created...");
JavaObjectequalsExample2 obj2 = new JavaObjectequalsExample2(2,3);
System.out.println("Objects are equal:" + obj1.equals(obj2));
}
}
输出:
1st object created... Addition of 10 and 20: Answer:30 2nd object created... Parameterized Constructors Addition 2 and 3 Answer:5 Objects are equal:false
相关用法
- Java Object hashCode()用法及代码示例
- Java Object toString()用法及代码示例
- Java Object getClass()用法及代码示例
- Java Object finalize()用法及代码示例
- Java ObjectInputStream readDouble()用法及代码示例
- Java ObjectStreamField getOffset()用法及代码示例
- Java ObjectStreamField compareTo()用法及代码示例
- Java ObjectInputStream readUnsignedByte()用法及代码示例
- Java ObjectInputStream readFields()用法及代码示例
- Java ObjectOutputStream writeFields()用法及代码示例
- Java ObjectInputStream readFully()用法及代码示例
- Java ObjectStreamField getName()用法及代码示例
- Java ObjectInputStream readInt()用法及代码示例
- Java ObjectStreamClass forClass()用法及代码示例
- Java ObjectInputStream read()用法及代码示例
- Java ObjectStreamField getTypeCode()用法及代码示例
- Java ObjectOutputStream writeBytes()用法及代码示例
- Java ObjectInputStream readUTF()用法及代码示例
- Java ObjectInputStream close()用法及代码示例
- Java ObjectOutputStream useProtocolVersion()用法及代码示例
注:本文由纯净天空筛选整理自 Java Object equals(Object obj) Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。