HashSet
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Under the hood, a HashSet is a HashMap whose keys are the elements. To find an element, Java:
1. calls hashCode() — a number that selects the "bucket";
2. compares the candidates in the bucket with equals().
Hence the rule: if two objects are equal by equals, they must have the same hashCode.
For String, Integer and the other standard classes this is already done. But for your own class, by default
equals compares references — two new Point(1, 2) objects will be different for a HashSet!
The solution is to override equals and hashCode, or to declare a record (Java 16+), which does it by itself:
record Point(int x, int y) { } // fields, a constructor, equals, hashCode, toString — automatically
Set<Point> visited = new HashSet<>();
visited.add(new Point(1, 2));
visited.contains(new Point(1, 2)) // true
Task. A robot starts at (0, 0) and moves by the commands U D L R (one line). Count how many
different cells it visited (including the start), and print yes if it ever came to a cell it had already
visited, otherwise no. Use a HashSet<Point> with a record Point.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.