חלקPart 3: OOP: היסודותOOP: the basics
כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
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.
הנקודות החשובותKey points
- equals: מתודה של
Objectשאומרת אם שני עצמים "שווים בתוכן".equals: AnObjectmethod saying whether two objects are "equal in content". - hashCode: מספר שמחושב מהתוכן של העצם.hashCode: A number computed from the object's content.
- שני ספרים עם אותו תוכן הם שני עצמים.Two books with the same content are two objects.
- בלי לדרוס את equals, גם היא בודקת "אותו עצם", בדיוק כמו
==.Without overriding equals, it also checks "the same object", exactly like==. equalsמשווה את השדות (עם instanceof עם משתנה),hashCodeמחושב מאותם שדות, ו-toStringנותן הדפסה קריאה.equalscompares the fields (with a pattern instanceof),hashCodeis computed from the same fields, andtoStringgives a readable print.- עכשיו
HashSetרואה שני ספרים זהים כספר אחד.Now aHashSetsees two identical books as one. - ל-
Tagיש equals אבל אין hashCode.Taghas equals but no hashCode. - לכל עצם יש hashCode אחר (לפי העצם, לא לפי התוכן), ולכן
HashSetמחפש במגירה הלא נכונה ושומר את "אותה" תגית פעמיים.Each object gets a different hashCode (by object, not by content), soHashSetlooks in the wrong drawer and keeps the "same" tag twice. - מדף, צעד 17: ספרים כפולים לא נכנסיםShelf, step 17: duplicates stay off
מונחיםTerms
- equalsequals: מתודה של
Objectשאומרת אם שני עצמים "שווים בתוכן". בלי לדרוס אותה היא בודקת==(אותו עצם). חתימה נכונה:public boolean equals(Object o).AnObjectmethod saying whether two objects are "equal in content". Unless overridden it checks==(the same object). The right signature:public boolean equals(Object o). - hashCodehashCode: מספר שמחושב מהתוכן של העצם.
HashSetו-HashMapמשתמשים בו כדי למצוא "מגירה" לפני שהם קוראים ל-equals.Objects.hash(a, b)מחשב אותו בקלות.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 ו-hashCodethe equals/hashCode contract: אם
a.equals(b), אזa.hashCode() == b.hashCode(). דורסים את שתיהן יחד, על סמך אותם שדות. equals גם צריכה להיות סימטרית:a.equals(b)אם ורק אםb.equals(a).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). - toStringtoString: המחרוזת שמייצגת עצם.
println(b),"x" + bו-List.toStringקוראים לה. בלי לדרוס יוצא משהו כמוBook@1b6d3586.The string that stands for an object.println(b),"x" + bandList.toStringcall it. Without an override you get something likeBook@1b6d3586. - @Override@Override: מבקש מ-javac לוודא שאתם באמת דורסים מתודה קיימת. אם החתימה שגויה (למשל
equals(Book)), javac עוצר:method does not override or implement a method from a supertype.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 עם משתנהpattern instanceof:
o instanceof Book otherבודק את הטיפוס וגם נותן משתנה מוכן מהטיפוס הזה, בלי המרה ידנית (Java 16 ומעלה).o instanceof Book otherchecks the type and gives a ready variable of that type, with no manual cast (Java 16 and up). - equalsequals: מתודה של
Objectשאומרת אם שני עצמים "שווים בתוכן". בלי לדרוס אותה היא בודקת==(אותו עצם). חתימה נכונה:public boolean equals(Object o).AnObjectmethod saying whether two objects are "equal in content". Unless overridden it checks==(the same object). The right signature:public boolean equals(Object o). - hashCodehashCode: מספר שמחושב מהתוכן של העצם.
HashSetו-HashMapמשתמשים בו כדי למצוא "מגירה" לפני שהם קוראים ל-equals.Objects.hash(a, b)מחשב אותו בקלות.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 ו-hashCodethe equals/hashCode contract: אם
a.equals(b), אזa.hashCode() == b.hashCode(). דורסים את שתיהן יחד, על סמך אותם שדות. equals גם צריכה להיות סימטרית:a.equals(b)אם ורק אםb.equals(a).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). - toStringtoString: המחרוזת שמייצגת עצם.
println(b),"x" + bו-List.toStringקוראים לה. בלי לדרוס יוצא משהו כמוBook@1b6d3586.The string that stands for an object.println(b),"x" + bandList.toStringcall it. Without an override you get something likeBook@1b6d3586. - @Override@Override: מבקש מ-javac לוודא שאתם באמת דורסים מתודה קיימת. אם החתימה שגויה (למשל
equals(Book)), javac עוצר:method does not override or implement a method from a supertype.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 עם משתנהpattern instanceof:
o instanceof Book otherבודק את הטיפוס וגם נותן משתנה מוכן מהטיפוס הזה, בלי המרה ידנית (Java 16 ומעלה).o instanceof Book otherchecks the type and gives a ready variable of that type, with no manual cast (Java 16 and up).
Cheatsheet
בלי equals: רק אותו עצם שווהWithout equals: only the same object is equal
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));equals, hashCode ו-toString יחדequals, hashCode and toString together
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);equals בלי hashCode: HashSet מתבלבלequals without hashCode: HashSet gets confused
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());שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|