Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Convex Hull Implementation in Java

19 min readadvanced
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Convex Hull runs in O(n log n) time and O(n) space, in Java as in every other language.
  • ✓No hull anywhere in the JDK. java.awt.geom.Point2D.Double gives double-precision points, java.awt.Polygon is int-only and meant for rendering, and java.awt.geom.Path2D.Double is what you build the finished ring into for drawing.
  • ✓java.util.Stack is rejected on sight because it extends the synchronised Vector; use ArrayDeque, or an ArrayList treated as a stack so you can index two from the top.
  • ✓The Java trap: Java is the one runtime here that actively detects a broken comparator and throws. Write the tempting (a, b) -> (int) (a.getX() - b.getX()) and two things go wrong at once: the cast truncates toward zero, so any two points less than 1.0 apart compare equal while a third point orders them apart, and that alone destroys transitivity (for huge coordinates the narrowing conversion saturates to Integer.MAX_VALUE rather than wrapping, JLS 5.1.3, so the sign survives -- the truncation is what kills you).
  • ✓Every Point2D.Double is a separate heap object with a header, so an n-point sort chases n pointers around memory; the standard rewrite when this gets hot is two double[] arrays sorted by an index permutation, because Arrays.sort(double[]) is dual-pivot quicksort with no comparator call at all.

What Convex Hull actually is

The convex hull of a point set is the smallest convex polygon containing every point: the shape a rubber band snaps to. The divide-and-conquer form sorts by x, hulls each half recursively, then stitches the halves with an upper and a lower tangent in linear time, giving O(n log n) worst case. Quickhull is the other divide step (average O(n log n), worst O(n^2)). Engineers reach for a hull in collision broad-phase, GIS footprints, outlier boundaries, and as step one of rotating calipers for diameter, min-width and min-area rectangle. Andrew's monotone chain -- sort once, then two linear scans -- hits the same bound with a far simpler merge, and is what most production code actually ships.

Convex Hull in Java: what you actually reach for

No hull anywhere in the JDK. java.awt.geom.Point2D.Double gives double-precision points, java.awt.Polygon is int-only and meant for rendering, and java.awt.geom.Path2D.Double is what you build the finished ring into for drawing. The sort is List.sort or Arrays.sort with Comparator.comparingDouble(Point2D::getX).thenComparingDouble(Point2D::getY). For anything geospatial the ecosystem standard is JTS: org.locationtech.jts.algorithm.ConvexHull, constructed from a Geometry or a Coordinate[], whose getConvexHull() returns a Geometry -- usually a Polygon, but a LineString or Point for degenerate inputs, which callers forget to handle.

Java implementation

java.util.Stack is rejected on sight because it extends the synchronised Vector; use ArrayDeque, or an ArrayList treated as a stack so you can index two from the top. Hand-written comparators lose to the Comparator.comparingDouble(...).thenComparingDouble(...) chain. The public method takes List<Point2D> and returns List.copyOf(hull) rather than the mutable internal list, and returning a subList view instead of a copy gets flagged, as does any raw type in the signature.
java
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public final class ConvexHull {
    private ConvexHull() {}

    private static double cross(Point2D o, Point2D a, Point2D b) {
        return (a.getX() - o.getX()) * (b.getY() - o.getY())
             - (a.getY() - o.getY()) * (b.getX() - o.getX());
    }

    private static List<Point2D> chain(List<Point2D> pts) {
        List<Point2D> h = new ArrayList<>();
        for (Point2D p : pts) {
            while (h.size() >= 2
                    && cross(h.get(h.size() - 2), h.get(h.size() - 1), p) <= 0) {
                h.remove(h.size() - 1);
            }
            h.add(p);
        }
        h.remove(h.size() - 1);
        return h;
    }

    public static List<Point2D> of(List<Point2D> input) {
        List<Point2D> pts = new ArrayList<>(input);
        // Double.compare inside comparingDouble: never (int)(a - b).
        pts.sort(Comparator.comparingDouble(Point2D::getX)
                           .thenComparingDouble(Point2D::getY));
        if (pts.size() < 3) return List.copyOf(pts);

        List<Point2D> hull = new ArrayList<>(chain(pts));
        Collections.reverse(pts);
        hull.addAll(chain(pts));
        return List.copyOf(hull);
    }
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Java-specific trap

Java is the one runtime here that actively detects a broken comparator and throws. Write the tempting (a, b) -> (int) (a.getX() - b.getX()) and two things go wrong at once: the cast truncates toward zero, so any two points less than 1.0 apart compare equal while a third point orders them apart, and that alone destroys transitivity (for huge coordinates the narrowing conversion saturates to Integer.MAX_VALUE rather than wrapping, JLS 5.1.3, so the sign survives -- the truncation is what kills you). Arrays.sort on objects is TimSort, and TimSort verifies its merge invariants, so instead of a quietly wrong hull you get IllegalArgumentException: Comparison method violates its general contract! thrown from deep inside the JDK -- on some inputs only, usually in production, never in the unit test. Use Double.compare or comparingDouble.

Performance in Java, beyond the O(n log n)

Every Point2D.Double is a separate heap object with a header, so an n-point sort chases n pointers around memory; the standard rewrite when this gets hot is two double[] arrays sorted by an index permutation, because Arrays.sort(double[]) is dual-pivot quicksort with no comparator call at all. ArrayList.get is a checked array read, and remove(size - 1) is O(1) but nulls the slot. Escape analysis rarely scalarises points that escape into a list. Expect C2 to need a few thousand iterations before the cross call inlines and the bounds checks fold. The asymptotic cost is the same in every language, O(n log n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Convex Hull between languages.

Real-World Applications

Convex Hull applies wherever its problem shape appears in your own code. In Java, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Convex Hull helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Convex Hull appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Convex Hull over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Convex Hull to build pattern recognition. In Java, demonstrate proficiency with generics and streams API to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Java code that is both correct and maintainable.

Frequently Asked Questions

Which Java type or library should I use for Convex Hull?

No hull anywhere in the JDK. java.awt.geom.Point2D.Double gives double-precision points, java.awt.Polygon is int-only and meant for rendering, and java.awt.geom.Path2D.Double is what you build the finished ring into for drawing. The sort is List.sort or Arrays.sort with Comparator.comparingDouble(Point2D::getX).thenComparingDouble(Point2D::getY). For anything geospatial the ecosystem standard is JTS: org.locationtech.jts.algorithm.ConvexHull, constructed from a Geometry or a Coordinate[], whose getConvexHull() returns a Geometry -- usually a Polygon, but a LineString or Point for degenerate inputs, which callers forget to handle.

What is the most common Java mistake when implementing Convex Hull?

Java is the one runtime here that actively detects a broken comparator and throws. Write the tempting (a, b) -> (int) (a.getX() - b.getX()) and two things go wrong at once: the cast truncates toward zero, so any two points less than 1.0 apart compare equal while a third point orders them apart, and that alone destroys transitivity (for huge coordinates the narrowing conversion saturates to Integer.MAX_VALUE rather than wrapping, JLS 5.1.3, so the sign survives -- the truncation is what kills you). Arrays.sort on objects is TimSort, and TimSort verifies its merge invariants, so instead of a quietly wrong hull you get IllegalArgumentException: Comparison method violates its general contract! thrown from deep inside the JDK -- on some inputs only, usually in production, never in the unit test. Use Double.compare or comparingDouble.

How does Convex Hull actually perform in Java?

Every Point2D.Double is a separate heap object with a header, so an n-point sort chases n pointers around memory; the standard rewrite when this gets hot is two double[] arrays sorted by an index permutation, because Arrays.sort(double[]) is dual-pivot quicksort with no comparator call at all. ArrayList.get is a checked array read, and remove(size - 1) is O(1) but nulls the slot. Escape analysis rarely scalarises points that escape into a list. Expect C2 to need a few thousand iterations before the cross call inlines and the bounds checks fold. Time complexity is O(n log n) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Before paying for GitHub Copilot, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.