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

JavaJava
17
חלק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.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • equals: מתודה של Object שאומרת אם שני עצמים "שווים בתוכן".equals: An Object method 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 נותן הדפסה קריאה.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.
  • מדף, צעד 17: ספרים כפולים לא נכנסיםShelf, step 17: duplicates stay off

מונחיםTerms

  • equalsequals: מתודה של Object שאומרת אם שני עצמים "שווים בתוכן". בלי לדרוס אותה היא בודקת == (אותו עצם). חתימה נכונה: public boolean equals(Object o).An Object method 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. HashSet and HashMap use 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).If a.equals(b), then a.hashCode() == b.hashCode(). Override both together, based on the same fields. equals must also be symmetric: a.equals(b) exactly when b.equals(a).
  • toStringtoString: המחרוזת שמייצגת עצם. println(b), "x" + b ו-List.toString קוראים לה. בלי לדרוס יוצא משהו כמו Book@1b6d3586.The string that stands for an object. println(b), "x" + b and List.toString call it. Without an override you get something like Book@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 other checks 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).An Object method 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. HashSet and HashMap use 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).If a.equals(b), then a.hashCode() == b.hashCode(). Override both together, based on the same fields. equals must also be symmetric: a.equals(b) exactly when b.equals(a).
  • toStringtoString: המחרוזת שמייצגת עצם. println(b), "x" + b ו-List.toString קוראים לה. בלי לדרוס יוצא משהו כמו Book@1b6d3586.The string that stands for an object. println(b), "x" + b and List.toString call it. Without an override you get something like Book@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 other checks 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

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