Point2D: Quick Reference 🌶️
Some problems ask your method to accept a Point2D parameter, or an ArrayList<Point2D>. Point2D is an object that represents a point on an ordinary (x, y) coordinate plane. You never reach into a Point2D's fields directly; call its methods instead.
You never build a
An
Point2D's geometry yourself — construct it with x and y, then call its methods.| Method | What it does |
|---|---|
new Point2D(x, y) | Creates a point at those coordinates (both double) |
p.getX() | Returns the x-coordinate, as a double |
p.getY() | Returns the y-coordinate, as a double |
p.distanceTo(other) | Returns the straight-line distance to another Point2D, as a double |
p.translate(dx, dy) | Returns a NEW Point2D shifted by dx/dy. p itself never changes |
p.equals(other) | Returns true if both points have the same x and y |
p.toString() | Returns the point as text, "(x, y)". Called automatically by System.out.println(p) |
Point2D a = new Point2D(0, 0);Point2D b = new Point2D(3, 4);double d = a.distanceTo(b); // 5.0boolean same = a.equals(b); // falsePoint2D c = a.translate(1, 1); // a new point, (1.0, 1.0) -- a itself is still (0, 0)System.out.println(b); // prints: (3.0, 4.0)
An
ArrayList<Point2D> works exactly like an ArrayList<Integer> or ArrayList<String> you've already used — points.get(i) gives you one Point2D, and points.size() gives you how many there are. The only difference is what you do once you have one: call .getX(), .getY(), or .distanceTo(...) on it, the same as any other Point2D.