lab20
subdirectory of your personal repo, the other submits a file report.txt
in the lab20
subdirectory of your personal repo.Point
like this:
public class Point { private int x; private int y; public Point(int x, int y) { this.x = x; this.y = y; } public String toString() { return getClass().getName() + "[x=" + x + ",y=" + y + "]"; } public boolean equals(Object otherObject) { if (!(otherObject instanceof Point)) return false; Point other = (Point) otherObject; return x == other.x && y == other.y; } }
import java.util.*; public class Prog1 { public static void main(String[] args) { Set<Point> set = new HashSet<>(); int n = 10; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) set.add(new Point(i % 2, j % 2)); System.out.println(set.size()); } }
n
to 1000. What does it print?Point
objects are inserted in the set?Point2
like this:
public class Point2 { private int x; private int y; public Point2(int x, int y) { this.x = x; this.y = y; } public String toString() { return getClass().getName() + "[x=" + x + ",y=" + y + "]"; } public int hashCode() { return x + y; } }
import java.util.*; public class Prog2 { public static void main(String[] args) { Set<Point2> set = new HashSet<>(); int n = 10; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) set.add(new Point2(i % 2, j % 2)); System.out.println(set.size()); } }
Point2
objects are inserted in the set?n
to 1000 and run the program again. Why does it seem to hang?Point2
to works correctly. Insert objects into the hash set as before. What count do you now get?LabeledPoint
of Point
:
public class LabeledPoint extends Point { private String label; public LabeledPoint(int x, int y, String label) { super(x, y); this.label = label; } public String toString() { return super.toString() + "[label=" + label + "]"; } }
public class Prog3 { public static void main(String[] args) { LabeledPoint p1 = new LabeledPoint(3, 4, "Fred"); LabeledPoint p2 = new LabeledPoint(3, 4, "Wilma"); System.out.println(p1.equals(p2)); } }What do you get? Why?
LabeledPoint.equals
. Then add this code:
Point p3 = new Point(3, 4); System.out.println(p1.equals(p3)); System.out.println(p3.equals(p1));What do you get? Why?
equals
is symmetrical?System.out.println(p1.equals(p3)); System.out.println(p3.equals(p2)); System.out.println(p1.equals(p2));If the first two are
true
, so should be the third.