package network3; import java.awt.geom.Point2D; import java.util.Collections; import java.util.HashSet; import java.util.Set; public class Network { private class UnmodifiablePoint extends Point2D { private final int x; private final int y; public UnmodifiablePoint(double x, double y) { this.x = (int)x; this.y = (int)y; } public void setLocation(double x, double y) { throw new UnsupportedOperationException(); } public double getX() { return x; } public double getY() { return y; } } private Set points = new HashSet<>(); private Set links = new HashSet<>(); private Point2D root; public Network(Point2D... points) { for (Point2D p : points) { this.points.add(new UnmodifiablePoint(p.getX(), p.getY())); } } public void setRoot(Point2D p) { if (! points.contains(p)) throw new IllegalArgumentException(); this.root = p; } public Point2D root() { return root; } public Set points() { return Collections.unmodifiableSet(points); } public void addLink(Point2D p1, Point2D p2) throws ExistingLinkException { Link l = link(p1, p2); if (l != null) throw new ExistingLinkException(l); links.add(new Link(p1, p2)); } public Set links() { return Collections.unmodifiableSet(links); } // Returns the link betweeen the points p1 and p2 if it exists, // null otherwise. public Link link(Point2D p1, Point2D p2) { for (Link l : links) if ((l.p1().equals(p1) && l.p2().equals(p2)) || (l.p2().equals(p1) && l.p1().equals(p2))) return l; return null; } }