נבנה על ידיBuilt by Ariel Yohimovich
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.
== מול 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. At the end we add a step to the companion project.מה נעשה היום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
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.המונחים של המפגש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).
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.Before the code, the words. Every term here is also linked in the course glossary.נושא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.
שני ספרים עם אותו תוכן הם שני עצמים. בלי לדרוס את 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.נושא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.
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.נושא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.
ל-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.נושאTopic 5
פרויקט מדףShelf project
הצעד של היום בפרויקט מדףToday's step in the Shelf project
- מדף, צעד 17: ספרים כפולים לא נכנסיםShelf, step 17: duplicates stay off
ל-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].equals: מתודה של Object שאומרת אם שני עצמים "שווים בתוכן".equals: An Object method saying whether two objects are "equal in content".
המונחים של המפגשThis session's termshashCode: מספר שמחושב מהתוכן של העצם.hashCode: A number computed from the object's content.
המונחים של המפגשThis session's termsהחוזה של equals ו-hashCode: אם a.equals(b), אז a.hashCode() == b.hashCode().the equals/hashCode contract: If a.equals(b), then a.hashCode() == b.hashCode().
המונחים של המפגשThis session's termstoString: המחרוזת שמייצגת עצם.toString: The string that stands for an object.
המונחים של המפגשThis session's terms@Override: מבקש מ-javac לוודא שאתם באמת דורסים מתודה קיימת.@Override: Asks javac to make sure you really override an existing method.
המונחים של המפגשThis session's termsinstanceof עם משתנה: 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).
המונחים של המפגשThis session's termsשני ספרים עם אותו תוכן הם שני עצמים.Two books with the same content are two objects.
בלי equals: רק אותו עצם שווהWithout equals: only the same object is equalבלי לדרוס את equals, גם היא בודקת "אותו עצם", בדיוק כמו ==.Without overriding equals, it also checks "the same object", exactly like ==.
בלי equals: רק אותו עצם שווהWithout equals: only the same object is equalבזיכרון רואים שני עצמים, ו-c מצביע על הראשון.In memory you see two objects, and c points to the first.
בלי equals: רק אותו עצם שווהWithout equals: only the same object is equalequals משווה את השדות (עם instanceof עם משתנה), hashCode מחושב מאותם שדות, ו-toString נותן הדפסה קריאה.equals compares the fields (with a pattern instanceof), hashCode is computed from the same fields, and toString gives a readable print.
equals, hashCode ו-toString יחדequals, hashCode and toString togetherעכשיו HashSet רואה שני ספרים זהים כספר אחד.Now a HashSet sees two identical books as one.
equals, hashCode ו-toString יחדequals, hashCode and toString togetherל-Tag יש equals אבל אין hashCode.Tag has equals but no hashCode.
equals בלי hashCode: HashSet מתבלבלequals without hashCode: HashSet gets confusedלכל עצם יש 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.
equals בלי hashCode: HashSet מתבלבלequals without hashCode: HashSet gets confusedזו הפרה של החוזה.That breaks the contract.
equals בלי hashCode: HashSet מתבלבלequals without hashCode: HashSet gets confusedמדף, צעד 17: ספרים כפולים לא נכנסיםShelf, step 17: duplicates stay off
הצעד של היום בפרויקט מדףToday's step in the Shelf projecta ו-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)?
truetruefalsefalse- שגיאת קומפילציהA compile error
- תלוי במזלIt depends on luck
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.falsefalse
נכון: שני עצמים שונים.Right: two different objects.דרסתם 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
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.לפי titleFrom title
נכון: אותם שדות כמו equals.Right: the same fields as equals.מה קורה כשכותבים @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
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.javac עוצר: זו לא דריסהjavac stops: it's not an override
נכון, ובשביל זה @Override קיים.Right, and that's what @Override is for.toString לנקודהtoString for a point
- הוסיפו ל-
Point את toString שמחזירה (3, 4).Add a toString to Point returning (3, 4).
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.צייד באגים: 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.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.אותו תלמיד, שם אחרThe same student, another name
- תלמידים שווים אם יש להם אותו
id (גם אם השם נכתב אחרת).Students are equal if they have the same id (even if the name is spelled differently).
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.נקודה כמפתחA point as a key
HashMap<Point, String> שומר שמות של מקומות.A HashMap<Point, String> stores place names.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.כמה עותקים?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.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מדף, צעד 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).
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.שברים שוויםEqual fractions
Fraction(1, 2) ו-Fraction(2, 4) צריכים להיות שווים.Fraction(1, 2) and Fraction(2, 4) should be equal.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.toString מקונןA nested toString
- ל-
Shelf יש שם ורשימת Book.Shelf has a name and a list of Book.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מה למדנו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
כל אחד אומר דבר אחד שלמד היום.Everyone says one thing they learned today.עכשיו לתרגולNow, practice
6 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית6 exercises and 2 challenges, auto-checked
מפנים לעמוד התרגול.Point to the practice page.