equals method
- Object class definition has:
- public boolean equals(Object obj)方法
- Provide a definition object "is equal to" logic
- Equals method of Object is defined as: x.equals (y) when x and y are the application returns true or false otherwise the same object
- J2SDK classes offered, such as String, Date, etc., override the equals method of Object, equals method call these classes, of x.equals (y), x and y when the object is referenced by the same type, and attributes of the content is equal to when (not necessarily of the same object) returns true or false otherwise
- Equals method can be overridden in the user-defined types as needed.
- public boolean equals(Object obj)方法
Example:
package com.nyist; public class TestEquals { public static void main(String[] args) { Cat c1 = new Cat(1,2,3); Cat c2 = new Cat(1,2,3); System.out.println(c1 == c2);
System.out.println(c1.equals(c2));
} } class Cat{ int color; int height,weight; public Cat(int color,int height,int weight) { this.color = color; this.height = height; this.weight = weight; } }
result:
false
false
The default implementation of equals method and == is the same, whether the comparison is all the same references.
By rewriting can be achieved only compare whether two objects essence is the same.
Example:
package com.nyist; public class TestEquals { public static void main(String[] args) { Cat c1 = new Cat(1,2,3); Cat c2 = new Cat(1,2,3); System.out.println(c1.equals(c2)); } } class Cat{ int color; int height,weight; public Cat(int color,int height,int weight) { this.color = color; this.height = height; this.weight = weight; } public boolean equals(Object obj){ if(obj == null) return false; else { if(obj instanceof Cat) { Cat c = (Cat)obj; if(c.color == this.color && c.height ==this.height && c.weight == this.weight) return true; } } return false; } }
result:
true