נבנה על ידיBuilt by Ariel Yohimovich

חזרה למפגשBack
JavaJava

equals, hashCode ו-toStringequals, hashCode & toString

מפגש 17: == מול equals, החוזה בין equals ל-hashCode, ולמה HashSet מתבלבל בלעדיהם. toString שעוזר לדבג.Session 17: == vs equals, the contract between equals and hashCode, and why a HashSet gets confused without them. A toString that helps debugging.

מה נעשה היוםToday's plan

  • מונחיםTerms
  • בלי equals: רק אותו עצם שווהWithout equals: only the same object is equal
  • equals, hashCode ו-toString יחדequals, hashCode and toString together
  • equals בלי hashCode: HashSet מתבלבלequals without hashCode: HashSet gets confused
  • פרויקט מדףShelf project
נושאTopic 1

מונחיםTerms

המונחים של המפגשThis session's terms

  • equals: מתודה של Object שאומרת אם שני עצמים "שווים בתוכן".equals: An Object method saying whether two objects are "equal in content".
  • hashCode: מספר שמחושב מהתוכן של העצם.hashCode: A number computed from the object's content.
  • החוזה של equals ו-hashCode: אם a.equals(b), אז a.hashCode() == b.hashCode().the equals/hashCode contract: If a.equals(b), then a.hashCode() == b.hashCode().
  • toString: המחרוזת שמייצגת עצם.toString: The string that stands for an object.
  • @Override: מבקש מ-javac לוודא שאתם באמת דורסים מתודה קיימת.@Override: Asks javac to make sure you really override an existing method.
  • instanceof עם משתנה: o instanceof Book other בודק את הטיפוס וגם נותן משתנה מוכן מהטיפוס הזה, בלי המרה ידנית (Java 16 ומעלה).pattern instanceof: o instanceof Book other checks the type and gives a ready variable of that type, with no manual cast (Java 16 and up).
נושאTopic 2

בלי equals: רק אותו עצם שווהWithout equals: only the same object is equal

בלי equals: רק אותו עצם שווהWithout equals: only the same object is equal

  • שני ספרים עם אותו תוכן הם שני עצמים.Two books with the same content are two objects.
  • בלי לדרוס את equals, גם היא בודקת "אותו עצם", בדיוק כמו ==.Without overriding equals, it also checks "the same object", exactly like ==.
  • בזיכרון רואים שני עצמים, ו-c מצביע על הראשון.In memory you see two objects, and c points to the first.
נושאTopic 3

equals, hashCode ו-toString יחדequals, hashCode and toString together

equals, hashCode ו-toString יחדequals, hashCode and toString together

  • equals משווה את השדות (עם instanceof עם משתנה), hashCode מחושב מאותם שדות, ו-toString נותן הדפסה קריאה.equals compares the fields (with a pattern instanceof), hashCode is computed from the same fields, and toString gives a readable print.
  • עכשיו HashSet רואה שני ספרים זהים כספר אחד.Now a HashSet sees two identical books as one.
נושאTopic 4

equals בלי hashCode: HashSet מתבלבלequals without hashCode: HashSet gets confused

equals בלי hashCode: HashSet מתבלבלequals without hashCode: HashSet gets confused

  • ל-Tag יש equals אבל אין hashCode.Tag has equals but no hashCode.
  • לכל עצם יש hashCode אחר (לפי העצם, לא לפי התוכן), ולכן HashSet מחפש במגירה הלא נכונה ושומר את "אותה" תגית פעמיים.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.
נושאTopic 5

פרויקט מדףShelf project

הצעד של היום בפרויקט מדףToday's step in the Shelf project

  • מדף, צעד 17: ספרים כפולים לא נכנסיםShelf, step 17: duplicates stay off

equals: מתודה של Object שאומרת אם שני עצמים "שווים בתוכן".equals: An Object method saying whether two objects are "equal in content".

hashCode: מספר שמחושב מהתוכן של העצם.hashCode: A number computed from the object's content.

החוזה של equals ו-hashCode: אם a.equals(b), אז a.hashCode() == b.hashCode().the equals/hashCode contract: If a.equals(b), then a.hashCode() == b.hashCode().

toString: המחרוזת שמייצגת עצם.toString: The string that stands for an object.

@Override: מבקש מ-javac לוודא שאתם באמת דורסים מתודה קיימת.@Override: Asks javac to make sure you really override an existing method.

instanceof עם משתנה: o instanceof Book other בודק את הטיפוס וגם נותן משתנה מוכן מהטיפוס הזה, בלי המרה ידנית (Java 16 ומעלה).pattern instanceof: o instanceof Book other checks the type and gives a ready variable of that type, with no manual cast (Java 16 and up).

שני ספרים עם אותו תוכן הם שני עצמים.Two books with the same content are two objects.

בלי לדרוס את equals, גם היא בודקת "אותו עצם", בדיוק כמו ==.Without overriding equals, it also checks "the same object", exactly like ==.

בזיכרון רואים שני עצמים, ו-c מצביע על הראשון.In memory you see two objects, and c points to the first.

equals משווה את השדות (עם instanceof עם משתנה), hashCode מחושב מאותם שדות, ו-toString נותן הדפסה קריאה.equals compares the fields (with a pattern instanceof), hashCode is computed from the same fields, and toString gives a readable print.

עכשיו HashSet רואה שני ספרים זהים כספר אחד.Now a HashSet sees two identical books as one.

ל-Tag יש equals אבל אין hashCode.Tag has equals but no hashCode.

לכל עצם יש hashCode אחר (לפי העצם, לא לפי התוכן), ולכן HashSet מחפש במגירה הלא נכונה ושומר את "אותה" תגית פעמיים.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.

מדף, צעד 17: ספרים כפולים לא נכנסיםShelf, step 17: duplicates stay off

a ו-b הם שני ספרים חדשים עם אותו תוכן, ול-Book אין equals. מה a.equals(b)?a and b are two new books with the same content, and Book has no equals. What's a.equals(b)?

  • truetrue
  • falsefalse
  • שגיאת קומפילציהA compile error
  • תלוי במזלIt depends on luck

falsefalse

דרסתם equals לפי title. לפי מה צריך לחשב את hashCode?You overrode equals by title. What should hashCode be computed from?

  • לפי titleFrom title
  • לפי כל השדות, גם אלה ש-equals לא בודקתFrom all fields, including ones equals ignores
  • מספר אקראיA random number
  • לא צריך hashCodeNo hashCode is needed

לפי titleFrom title

מה קורה כשכותבים @Override public boolean equals(Book b)?What happens when you write @Override public boolean equals(Book b)?

  • זה דורס את equalsIt overrides equals
  • javac עוצר: זו לא דריסהjavac stops: it's not an override
  • זה עובד רק ב-HashSetIt works only in a HashSet
  • זה זורק חריגה בריצהIt throws at runtime

javac עוצר: זו לא דריסהjavac stops: it's not an override

toString לנקודהtoString for a point

  • הוסיפו ל-Point את toString שמחזירה (3, 4).Add a toString to Point returning (3, 4).

צייד באגים: equals שלא נקראתBug hunter: an equals nobody calls

  • shelf.contains(new Book("Emma")) מחזירה false, למרות שיש equals.shelf.contains(new Book("Emma")) returns false, even though there's an equals.

אותו תלמיד, שם אחרThe same student, another name

  • תלמידים שווים אם יש להם אותו id (גם אם השם נכתב אחרת).Students are equal if they have the same id (even if the name is spelled differently).

נקודה כמפתחA point as a key

  • HashMap<Point, String> שומר שמות של מקומות.A HashMap<Point, String> stores place names.

כמה עותקים?How many copies?

  • static int countCopies(List<Book> shelf, Book wanted) סופרת כמה ספרים ברשימה שווים (equals) ל-wanted.static int countCopies(List<Book> shelf, Book wanted) counts how many books in the list equal (equals) wanted.

מדף, צעד 17: ספרים כפולים לא נכנסיםShelf, step 17: duplicates stay off

  • ל-Book (כותר וסופר) הוסיפו equals, hashCode ו-toString (Dune by Herbert).Add equals, hashCode and toString (Dune by Herbert) to Book (title and author).

שברים שוויםEqual fractions

  • Fraction(1, 2) ו-Fraction(2, 4) צריכים להיות שווים.Fraction(1, 2) and Fraction(2, 4) should be equal.

toString מקונןA nested toString

  • ל-Shelf יש שם ורשימת Book.Shelf has a name and a list of Book.

מה למדנוWhat we learned

  • equals: מתודה של Object שאומרת אם שני עצמים "שווים בתוכן".equals: An Object method saying whether two objects are "equal in content".
  • שני ספרים עם אותו תוכן הם שני עצמים.Two books with the same content are two objects.
  • equals משווה את השדות (עם instanceof עם משתנה), hashCode מחושב מאותם שדות, ו-toString נותן הדפסה קריאה.equals compares the fields (with a pattern instanceof), hashCode is computed from the same fields, and toString gives a readable print.
  • ל-Tag יש equals אבל אין hashCode.Tag has equals but no hashCode.
  • מדף, צעד 17: ספרים כפולים לא נכנסיםShelf, step 17: duplicates stay off

עכשיו לתרגולNow, practice

6 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית6 exercises and 2 challenges, auto-checked
הערות מרצהSpeaker notes

נבנה על ידיBuilt by Ariel Yohimovich