存储用于通过 x,y 坐标定位的对象
我正在尝试确定一种快速存储一组对象的方法,每个对象都有一个 x 和 y 坐标值,以便我可以快速检索某个矩形或圆形内的所有对象。 对于小型对象集(~100),简单地将它们存储在列表中并迭代它的简单方法相对较快。 然而,对于更大的群体来说,这预计会很慢。 我也尝试将它们存储在一对 TreeMap 中,一个按 x 坐标排序,一个按 y 坐标排序,使用以下代码:
xSubset = objectsByX.subSet( minX, maxX );
ySubset = objectsByY.subSet( minY, maxY );
result.addAll( xSubset );
result.retainAll( ySubset );
这也有效,对于较大的对象集来说速度更快,但仍然较慢比我想要的。 部分问题还在于这些对象会四处移动,并且需要重新插入到该存储中,这意味着将它们从树/列表中删除并重新添加到树/列表中。 我忍不住认为一定有更好的解决方案。 我正在用 Java 实现这个,如果它有什么区别的话,尽管我希望任何解决方案都将更多地采用有用的模式/算法的形式。
I'm trying to determine a fast way of storing a set of objects, each of which have an x and y coordinate value, such that I can quickly retrieve all objects within a certain rectangle or circle.
For small sets of objects (~100) the naive approach of simply storing them in a list, and iterating through it, is relatively quick. However, for much larger groups, that is expectedly slow.
I've tried storing them in a pair of TreeMaps as well, one sorted on the x coordinate, and one sorted on the y coordinate, using this code:
xSubset = objectsByX.subSet( minX, maxX );
ySubset = objectsByY.subSet( minY, maxY );
result.addAll( xSubset );
result.retainAll( ySubset );
This also works, and is faster for larger sets of objects, but is still slower than I would like.
Part of the problem is also that these objects move around, and need to be inserted back into this storage, which means removing them from and re-adding them to the trees/lists.
I can't help but think there must be better solutions out there.
I'm implementing this in Java, if it makes any difference, though I expect any solution will be more in the form of a useful pattern/algorithm.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
四叉树似乎解决了我问的具体问题。 Kd-Tree 是一种更通用的形式,适用于任意数量的维度,而不仅仅是两个维度。
如果存储的对象有一个边界矩形,那么 R-Trees 也可能很有用,而不是只是一个简单的点。
这些类型的结构的通用术语是空间索引。
有一个 Quadtree 的 Java 实现和R-Tree。
Quadtrees seem to solve the specific problem I asked. Kd-Trees are a more general form, for any number of dimensions, rather than just two.
R-Trees may also be useful if the objects being stored have a bounding rectangle, rather than being just a simple point.
The general term for these type of structures is Spatial Index.
There is a Java implementation of Quadtree and R-Tree.
一般术语是空间索引。 我想你应该根据现有实现进行选择。
The general term is a Spatial Index. I guess you should choose according to the existing implementations.
四叉树 是 结构 通常用于此目的。
A quadtree is the structure which is usually used for that.
看看 Kd-Trees。
Have a look at Kd-Trees.
C# 中的简单四叉树实现(易于翻译为 java)
http://www.codeproject.com/KB/recipes/QuadTree.aspx
Simple QuadTree implementation in C# (easy to translate into java)
http://www.codeproject.com/KB/recipes/QuadTree.aspx
您可以将所有 x 线放在一个地图中,将 y 线放在另一个地图中,并使地图值指向该对象。
You could put all the x cords in a map, and the y cords in another map, and have the map values point to the object.