8

So I came across some code that looks like this:

Polygon polygon = Polygon.Builder()
                .addVertex(new Point(38.085255f, -122.734590f))
                .addVertex(new Point(37.513400f, -122.726350f))
                .addVertex(new Point(37.044617f, -122.413239f))
                .addVertex(new Point(37.121307f, -121.765046f))
                .addVertex(new Point(37.497051f, -121.707368f))
                .addVertex(new Point(37.812351f, -121.905122f))
                .addVertex(new Point(37.899094f, -121.740327f))
                .addVertex(new Point(37.987900f, -121.877656f))
                .addVertex(new Point(37.886089f, -122.034211f))
                .addVertex(new Point(38.085247f, -122.366548f))
                .build();

This simply adds the points with float coordinates to an array and then at the end builds the polygon. Anyway, my question is if there is any easy way where I could loop through this addVertex process without having to change the basic structure of the process?

Basic idea of what I'm trying to do is:

for(int i = 0; i < vertices.length; i++) {
    polygon.Builder.addVertex(new Point(vertices[i].getX(), vertices[i].getY());
}
polygon.Builder().build();

I tried to generalize this example as much as possible and hopefully I didn't add any confusion in the process.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
whla
  • 739
  • 1
  • 12
  • 26
  • It really depends where the coordinates are coming from. It seems like you've already figured out how to solve the problem, though - are you just looking for an implementation? – x4nd3r Sep 17 '14 at 22:39

2 Answers2

12

With this method-chaining builder pattern, the key is to recognize that each call to addVertex returns a (new) builder. To loop this, you can repeatedly overwrite the current builder with a new one each iteration.

PolygonBuilder builder = Polygon.Builder();

for (int i = 0; i < vertices.length; i++) {
    builder = builder.addVertex(new Point(vertices[i].getX(), vertices[i].getY());
}

Polygon polygon = builder.build();

This works whether each addVertex call returns a new builder or whether it returns the same builder each time. Either way.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

Yes. That should work. The calls do not have to be made on the same line. Therefore it would work in a loop.

System.out.println(new StringBuilder().append(1).append(2).append(3).toString());

is the same as

StringBuilder sb = new StringBuilder();
sb.append(1);
sb.append(2);
sb.append(3);
System.out.println(sb.toString());

which is same as

StringBuilder sb = new StringBuilder();
for(int i=1; i<=3; i++) {
  sb.append(i);
}
System.out.println(sb.toString());
JustinKSU
  • 4,875
  • 2
  • 29
  • 51