1
CSE 331
The Object class; Object equality and the equals method
slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/
CSE 331 The Object class; Object equality and the equals method - - PowerPoint PPT Presentation
CSE 331 The Object class; Object equality and the equals method slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/ 1 The class Object The class Object
1
slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/
2
3
text representation of the object public String toString() methods related to concurrency and locking (seen later) public void notify() public void notifyAll() public void wait() public void wait(...) a code suitable for putting this
public int hashCode() info about the object's type public Class<?> getClass() called during garbage collection protected void finalize() returns whether two objects have the same state public boolean equals(Object o) creates a copy of the object protected Object clone() description method
4
5
6
Point p1 = new Point(5, 3); Point p2 = new Point(5, 3); Point p3 = p2; // p1 == p2 is false; // p1 == p3 is false; // p2 == p3 is true // p1.equals(p2)? // p2.equals(p3)?
...
x 5 y 3 p1 p2
...
x 5 y 3 p3
7
public class Object { ... public boolean equals(Object o) { return this == o; } }
8
9
10
11
12
13
14
15
16
false null instanceof Object false p instanceof String true p instanceof Object false null instanceof String true s instanceof Object true p instanceof Point true s instanceof String false s instanceof Point
result expression
17
18
19
20
21
22
public boolean equals(Object o) { // Point if (o != null && getClass() == o.getClass()) { Point other = (Point) o; return x == other.x && y == other.y; } else { return false; } } public boolean equals(Object o) { // Point3D if (o != null && getClass() == o.getClass()) { Point3D other = (Point3D) o; return super.equals(o) && z == other.z; } else { return false; } }
23
24
Date d1 = new Date(0); // Jan 1 1970 00:00:00 GMT Date d2 = new Date(0); System.out.println(d1.equals(d2)); // true d2.setTime(1); // 1 millisecond later System.out.println(d1.equals(d2)); // false
25
26
Set<String> set1 = new HashSet<String>(); Set<String> set2 = new TreeSet<String>(); for (String s : "hi how are you".split(" ")) { set1.add(s); set2.add(s); } System.out.println(set1.equals(set2)); // true