矩形列表的并集
我有一个 AWT 矩形列表。我想以一种优雅的方式计算矩形的并集。这是我的代码,它可以工作,但看起来不太优雅。
Rectangle union(List<Rectangle> rects) {
if (rects.isEmpty()) {
return new Rectangle();
}
assert !rects.isEmpty();
final Iterator<Rectangle> iterator = rects.iterator();
Rectangle rect = iterator.next();
while (iterator.hasNext()) {
rect = rect.union( iterator.next() );
}
return rect;
}
我还尝试了以下不起作用的方法:
Rectangle union(List<Rectangle> rects) {
Rectangle result = new Rectangle();
for (Rectangle rect : rects) {
result.add( rect );
}
return result;
}
矩形结果初始化为 (0,0,0,0),因此联合将始终包含原点。
在 Java 中是否有更优雅的方法来做到这一点?
I have a list of AWT rectangles. I want to compute the union of the rectangles in an elegant way. Here is my code which works but does not look very elegant.
Rectangle union(List<Rectangle> rects) {
if (rects.isEmpty()) {
return new Rectangle();
}
assert !rects.isEmpty();
final Iterator<Rectangle> iterator = rects.iterator();
Rectangle rect = iterator.next();
while (iterator.hasNext()) {
rect = rect.union( iterator.next() );
}
return rect;
}
I also tried the following which does not work:
Rectangle union(List<Rectangle> rects) {
Rectangle result = new Rectangle();
for (Rectangle rect : rects) {
result.add( rect );
}
return result;
}
The rectangle result is initialized to (0,0,0,0) so the union will allways contain the origin.
Is there a more elegant way to do this in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在第二个示例中,您需要像这样初始化
result
:请注意,这仅在 Java SE 6 后有效。在以前的版本中,有关负宽度和高度的行为未定义。请参阅
Rectangle
的 Javadoc 条目 具有一组点的类似示例。In your second example, you need to initialize
result
like this:Be aware that this only works since Java SE 6. In previous versions the behaviour with regards to negative widths and heights is undefined. See the Javadoc entry for
Rectangle
for a similar example with a set of points.我认为你的解决方案还不错。以下是我的做法:
输出是
一些注释:
如果列表
矩形
为空,我会抛出异常而不是返回矩形
Rectangle.union
和Rectangle.add
给出相同的结果(参见输出)我会从一个新的
Rectangle< /code> 等于
rects
的第一个元素,然后用它来计算与以下元素的并集(或者等效地,添加以下元素)。我希望这有帮助。
I think your solution is not bad. Here is how I would do it:
Output is
Some notes:
If the list
rects
is empty, I would throw an exception rather than returning aRectangle
both
Rectangle.union
andRectangle.add
give the same results (see output)I would start with a new
Rectangle
equal to the first element ofrects
and then use it to compute the union with the following ones (or, equivalently, add the following ones).I hope this helps.
根据随附的 javadoc,您基于
add
的应该可以工作。它说:但它只起作用,您初始化尺寸小于零的矩形。以下是方法 2 的可行解决方案:
替代:根据第一个列表项创建初始结果:
According the accompanying javadoc, your
add
based should work. It says:But it only works, you initialize the rectangle with a dimension less than zero. Here's a working solution for method 2:
Alternative: create the initial result based on the first list item: