equals, hashCode ו-toStringequals, hashCode & toString
== מול equals, החוזה בין equals ל-hashCode, ולמה HashSet מתבלבל בלעדיהם. toString שעוזר לדבג.
== vs equals, the contract between equals and hashCode, and why a HashSet gets confused without them. A toString that helps debugging.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- equals: מתודה של
Objectשאומרת אם שני עצמים "שווים בתוכן". בלי לדרוס אותה היא בודקת==(אותו עצם). חתימה נכונה:public boolean equals(Object o).equals: AnObjectmethod saying whether two objects are "equal in content". Unless overridden it checks==(the same object). The right signature:public boolean equals(Object o). - hashCode: מספר שמחושב מהתוכן של העצם.
HashSetו-HashMapמשתמשים בו כדי למצוא "מגירה" לפני שהם קוראים ל-equals.Objects.hash(a, b)מחשב אותו בקלות.hashCode: A number computed from the object's content.HashSetandHashMapuse it to find a "drawer" before calling equals.Objects.hash(a, b)computes it easily. - החוזה של equals ו-hashCode: אם
a.equals(b), אזa.hashCode() == b.hashCode(). דורסים את שתיהן יחד, על סמך אותם שדות. equals גם צריכה להיות סימטרית:a.equals(b)אם ורק אםb.equals(a).the equals/hashCode contract: Ifa.equals(b), thena.hashCode() == b.hashCode(). Override both together, based on the same fields. equals must also be symmetric:a.equals(b)exactly whenb.equals(a). - toString: המחרוזת שמייצגת עצם.
println(b),"x" + bו-List.toStringקוראים לה. בלי לדרוס יוצא משהו כמוBook@1b6d3586.toString: The string that stands for an object.println(b),"x" + bandList.toStringcall it. Without an override you get something likeBook@1b6d3586. - @Override: מבקש מ-javac לוודא שאתם באמת דורסים מתודה קיימת. אם החתימה שגויה (למשל
equals(Book)), javac עוצר:method does not override or implement a method from a supertype.@Override: Asks javac to make sure you really override an existing method. With a wrong signature (e.g.equals(Book)), javac stops:method does not override or implement a method from a supertype. - instanceof עם משתנה:
o instanceof Book otherבודק את הטיפוס וגם נותן משתנה מוכן מהטיפוס הזה, בלי המרה ידנית (Java 16 ומעלה).pattern instanceof:o instanceof Book otherchecks the type and gives a ready variable of that type, with no manual cast (Java 16 and up).
02בלי equals: רק אותו עצם שווהWithout equals: only the same object is equal
שני ספרים עם אותו תוכן הם שני עצמים. בלי לדרוס את equals, גם היא בודקת "אותו עצם", בדיוק כמו ==. בזיכרון רואים שני עצמים, ו-c מצביע על הראשון.
Two books with the same content are two objects. Without overriding equals, it also checks "the same object", exactly like ==. In memory you see two objects, and c points to the first.
public class Main {
public static void main(String[] args) {
Book a = new Book("Dune", 1965);
Book b = new Book("Dune", 1965);
Book c = a;
System.out.println((a == b) + " " + a.equals(b) + " " + (a == c));
}
}
class Book {
String title;
int year;
Book(String title, int year) {
this.title = title;
this.year = year;
}
}false false true
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מה קורה עכשיוWhat happens now
פלטOutput
Stack: משתנים בכל מתודהStack: each method's variables
Heap: העצמיםHeap: the objects
03equals, hashCode ו-toString יחדequals, hashCode and toString together
equals משווה את השדות (עם instanceof עם משתנה), hashCode מחושב מאותם שדות, ו-toString נותן הדפסה קריאה. עכשיו HashSet רואה שני ספרים זהים כספר אחד.
equals compares the fields (with a pattern instanceof), hashCode is computed from the same fields, and toString gives a readable print. Now a HashSet sees two identical books as one.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Book a = new Book("Dune", 1965);
Book b = new Book("Dune", 1965);
System.out.println(a.equals(b) + " " + (a.hashCode() == b.hashCode()));
Set<Book> shelf = new HashSet<>();
shelf.add(a);
shelf.add(b);
System.out.println(shelf.size() + " " + shelf);
}
}
class Book {
private final String title;
private final int year;
Book(String title, int year) {
this.title = title;
this.year = year;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Book other)) {
return false;
}
return year == other.year && title.equals(other.title);
}
@Override
public int hashCode() {
return Objects.hash(title, year);
}
@Override
public String toString() {
return title + " (" + year + ")";
}
}true true 1 [Dune (1965)]
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04equals בלי hashCode: HashSet מתבלבלequals without hashCode: HashSet gets confused
ל-Tag יש equals אבל אין hashCode. לכל עצם יש hashCode אחר (לפי העצם, לא לפי התוכן), ולכן HashSet מחפש במגירה הלא נכונה ושומר את "אותה" תגית פעמיים. זו הפרה של החוזה.
Tag has equals but no hashCode. Each object gets a different hashCode (by object, not by content), so HashSet looks in the wrong drawer and keeps the "same" tag twice. That breaks the contract.
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<Tag> tags = new HashSet<>();
tags.add(new Tag("java"));
tags.add(new Tag("java"));
System.out.println(new Tag("java").equals(new Tag("java")) + " " + tags.size());
}
}
class Tag {
final String name;
Tag(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
return o instanceof Tag t && name.equals(t.name);
}
}true 2
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05הצעד של היום בפרויקט מדףToday's step in the Shelf project
ל-Book (כותר וסופר) הוסיפו equals, hashCode ו-toString (Dune by Herbert). הכניסו ל-LinkedHashSet את Dune, Emma ושוב Dune. add מחזירה false לכפול, ואז הדפיסו Skipped duplicate: Dune by Herbert. בסוף הדפיסו את המדף: [Dune by Herbert, Emma by Austen].
Add equals, hashCode and toString (Dune by Herbert) to Book (title and author). Put Dune, Emma and Dune again into a LinkedHashSet. add returns false for the duplicate, so print Skipped duplicate: Dune by Herbert. Finally print the shelf: [Dune by Herbert, Emma by Austen].
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.