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.
toString לנקודהtoString for a point
תזכורת: מה ביקשוReminder: the task
הוסיפו ל-Point את toString שמחזירה (3, 4). הדפיסו את הנקודה לבד, בתוך מחרוזת (Point: (3, 4)), ובתוך רשימה: [(1, 2), (3, 4)].
Add a toString to Point returning (3, 4). Print the point alone, inside a string (Point: (3, 4)), and inside a list: [(1, 2), (3, 4)].
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.List;
public class Main {
public static void main(String[] args) {
Point p = new Point(3, 4);
System.out.println(p);
System.out.println("Point: " + p);
System.out.println(List.of(new Point(1, 2), p));
}
}
class Point {
private final int x;
private final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}(3, 4) Point: (3, 4) [(1, 2), (3, 4)]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
צייד באגים: equals שלא נקראתBug hunter: an equals nobody calls
תזכורת: מה ביקשוReminder: the task
shelf.contains(new Book("Emma")) מחזירה false, למרות שיש equals. הוסיפו @Override מעל ה-equals ותראו מה javac אומר, ואז תקנו כך שיודפס true.
shelf.contains(new Book("Emma")) returns false, even though there's an equals. Add @Override above the equals and see what javac says, then fix it so it prints true.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Book> shelf = List.of(new Book("Dune"), new Book("Emma"));
System.out.println(shelf.contains(new Book("Emma")));
}
}
class Book {
final String title;
Book(String title) {
this.title = title;
}
@Override
public boolean equals(Object o) {
return o instanceof Book other && title.equals(other.title);
}
@Override
public int hashCode() {
return title.hashCode();
}
}true
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
אותו תלמיד, שם אחרThe same student, another name
תזכורת: מה ביקשוReminder: the task
תלמידים שווים אם יש להם אותו id (גם אם השם נכתב אחרת). כתבו equals ו-hashCode לפי id בלבד. הוסיפו ל-HashSet את 101 Noa, 102 Avi, 101 Noa L., והדפיסו 2 ואז true (ל-contains של 102).
Students are equal if they have the same id (even if the name is spelled differently). Write equals and hashCode by id only. Add 101 Noa, 102 Avi, 101 Noa L. to a HashSet, and print 2 then true (for contains of 102).
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<Student> course = new HashSet<>();
course.add(new Student(101, "Noa"));
course.add(new Student(102, "Avi"));
course.add(new Student(101, "Noa L."));
System.out.println(course.size());
System.out.println(course.contains(new Student(102, "?")));
}
}
class Student {
private final int id;
private final String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object o) {
return o instanceof Student s && id == s.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}2 true
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
נקודה כמפתחA point as a key
תזכורת: מה ביקשוReminder: the task
HashMap<Point, String> שומר שמות של מקומות. כדי ש-get(new Point(1, 2)) ימצא את home, ל-Point צריך equals ו-hashCode. הדפיסו home ואז nothing (ל-(9, 9) עם getOrDefault).
A HashMap<Point, String> stores place names. For get(new Point(1, 2)) to find home, Point needs equals and hashCode. Print home then nothing (for (9, 9) with getOrDefault).
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class Main {
public static void main(String[] args) {
Map<Point, String> places = new HashMap<>();
places.put(new Point(1, 2), "home");
places.put(new Point(5, 5), "park");
System.out.println(places.get(new Point(1, 2)));
System.out.println(places.getOrDefault(new Point(9, 9), "nothing"));
}
}
class Point {
private final int x;
private final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
return o instanceof Point p && x == p.x && y == p.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}home nothing
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
כמה עותקים?How many copies?
תזכורת: מה ביקשוReminder: the task
static int countCopies(List<Book> shelf, Book wanted) סופרת כמה ספרים ברשימה שווים (equals) ל-wanted. ספרים שווים אם הכותר והסופר זהים. עבור מדף עם Dune פעמיים, הדפיסו 2, ואז 0 עבור Dune של סופר אחר.
static int countCopies(List<Book> shelf, Book wanted) counts how many books in the list equal (equals) wanted. Books are equal if title and author match. For a shelf with Dune twice, print 2, then 0 for a Dune by another author.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.List;
import java.util.Objects;
public class Main {
static int countCopies(List<Book> shelf, Book wanted) {
int n = 0;
for (Book b : shelf) {
if (b.equals(wanted)) {
n++;
}
}
return n;
}
public static void main(String[] args) {
List<Book> shelf = List.of(new Book("Dune", "Herbert"), new Book("Emma", "Austen"), new Book("Dune", "Herbert"));
System.out.println(countCopies(shelf, new Book("Dune", "Herbert")));
System.out.println(countCopies(shelf, new Book("Dune", "Someone")));
}
}
class Book {
private final String title;
private final String author;
Book(String title, String author) {
this.title = title;
this.author = author;
}
@Override
public boolean equals(Object o) {
return o instanceof Book b && title.equals(b.title) && author.equals(b.author);
}
@Override
public int hashCode() {
return Objects.hash(title, author);
}
}2 0
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 17: ספרים כפולים לא נכנסיםShelf, step 17: duplicates stay off
תזכורת: מה ביקשוReminder: the task
ל-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].
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Book[] incoming = {new Book("Dune", "Herbert"), new Book("Emma", "Austen"), new Book("Dune", "Herbert")};
Set<Book> shelf = new LinkedHashSet<>();
for (Book b : incoming) {
if (!shelf.add(b)) {
System.out.println("Skipped duplicate: " + b);
}
}
System.out.println(shelf);
}
}
class Book {
private final String title;
private final String author;
Book(String title, String author) {
this.title = title;
this.author = author;
}
@Override
public boolean equals(Object o) {
return o instanceof Book b && title.equals(b.title) && author.equals(b.author);
}
@Override
public int hashCode() {
return Objects.hash(title, author);
}
@Override
public String toString() {
return title + " by " + author;
}
}Skipped duplicate: Dune by Herbert [Dune by Herbert, Emma by Austen]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
שברים שוויםEqual fractions
תזכורת: מה ביקשוReminder: the task
Fraction(1, 2) ו-Fraction(2, 4) צריכים להיות שווים. צמצמו בבנאי (עם gcd), ואז equals ו-hashCode פשוטים עובדים. הדפיסו true true (סימטריה), ואז 2 1/2 (גודל ה-Set אחרי הוספת 2/4, ו-toString של 2/4).
Fraction(1, 2) and Fraction(2, 4) should be equal. Reduce in the constructor (with gcd), and then simple equals and hashCode work. Print true true (symmetry), then 2 1/2 (the Set's size after adding 2/4, and 2/4's toString).
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Fraction half = new Fraction(1, 2);
Fraction twoQuarters = new Fraction(2, 4);
System.out.println(half.equals(twoQuarters) + " " + twoQuarters.equals(half));
Set<Fraction> set = new HashSet<>(Set.of(half, new Fraction(3, 4)));
set.add(twoQuarters);
System.out.println(set.size() + " " + twoQuarters);
}
}
class Fraction {
private final int num;
private final int den;
Fraction(int num, int den) {
int g = gcd(num, den);
this.num = num / g;
this.den = den / g;
}
private static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
@Override
public boolean equals(Object o) {
return o instanceof Fraction f && num == f.num && den == f.den;
}
@Override
public int hashCode() {
return Objects.hash(num, den);
}
@Override
public String toString() {
return num + "/" + den;
}
}true true 2 1/2
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
toString מקונןA nested toString
תזכורת: מה ביקשוReminder: the task
ל-Shelf יש שם ורשימת Book. ה-toString שלו משתמש ב-toString של הרשימה, שקוראת ל-toString של כל ספר. הדפיסו Fiction(2): [Dune (1965), Emma (1815)].
Shelf has a name and a list of Book. Its toString uses the list's toString, which calls each book's toString. Print Fiction(2): [Dune (1965), Emma (1815)].
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Shelf s = new Shelf("Fiction");
s.add(new Book("Dune", 1965));
s.add(new Book("Emma", 1815));
System.out.println(s);
}
}
class Shelf {
private final String name;
private final List<Book> books = new ArrayList<>();
Shelf(String name) {
this.name = name;
}
void add(Book b) {
books.add(b);
}
@Override
public String toString() {
return name + "(" + books.size() + "): " + books;
}
}
class Book {
private final String title;
private final int year;
Book(String title, int year) {
this.title = title;
this.year = year;
}
@Override
public String toString() {
return title + " (" + year + ")";
}
}Fiction(2): [Dune (1965), Emma (1815)]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.