how to calculate centroid of an arraylist of points

user2398101 picture user2398101 · Sep 3, 2013 · Viewed 14.6k times · Source

I am trying to add up all the x and y coordiantes respectively from points of ArrayList.

public static ArrayList knots = new ArrayList<Point>();



public Point centroid()  {
        Point center = new Point();
            for(int i=0; i<knots.size(); i++) {
            ????????????????????
        return center;
}

How do I find the centroid ??

Answer

Philipp Sander picture Philipp Sander · Sep 3, 2013
public Point centroid()  {
    double centroidX = 0, centroidY = 0;

        for(Point knot : knots) {
            centroidX += knot.getX();
            centroidY += knot.getY();
        }
    return new Point(centroidX / knots.size(), centroidY / knots.size());
}