我有一个集合 (List<Rectangle>),我需要对它进行左右排序。那部分很容易。然后我想以原始顺序遍历矩形,但很容易在排序集合中找到它们的索引。indexOf() 不起作用,因为我可能有许多相等的对象。我不禁觉得应该有一个简单的方法来做到这一点。
Draemon
问问题
1704 次
4 回答
2
如果您没有数以万计的对象,您可以将它们存储在两个单独的集合中,一个是原始的,一个是排序的。请记住,Java 中的集合类仅存储对对象的引用,因此它不会像看起来那样占用太多内存。
于 2008-10-16T00:06:32.820 回答
2
我找到了一个解决方案 - 但也许有一个更整洁/更优化的解决方案。
List<Rectangle> originalRects = ...;
/* record index of each rectangle object.
* Using a hash map makes lookups efficient,
* and using an IdentityHashMap means we lookup by object identity
* not value.
*/
IdentityHashMap<Rectangle, Integer> originalIndices = new IdentityHashMap<Rectangle, Integer>();
for(int i=0; i<originalRects.size(); i++) {
originalIndices.put(originalRects.get(i), i);
}
/* copy rectangle list */
List<Rectangle> sortedRects = new ArrayList<Rectangle>();
sortedRects.addAll(originalRects);
/* and sort */
Collections.sort(sortedRects, new LeftToRightComparator());
/* Loop through original list */
for(int i=0; i<sortedRects.size(); i++) {
Rectangle rect = sortedRects.get(i);
/* Lookup original index efficiently */
int origIndex = originalIndices.get(rect);
/* I know the original, and sorted indices plus the rectangle itself */
...
于 2008-10-16T00:29:25.270 回答
0
克隆列表并对其中一个进行排序。对同一个对象有两个引用对 indexOf() 来说并不重要,因为指向同一个对象的指针是相同的,你无法分辨它们。如果您有两个相等但不相同的对象,并且您确实想区分它们,那么您确实遇到了问题,因为 indexOf() 正在使用 equal 方法。在这种情况下,最好的解决方案可能是简单地遍历列表并检查对象身份 (==)。
于 2008-10-16T00:16:53.063 回答
0
另一种方法是对索引数组进行排序,而不是对原始列表进行排序。该数组以标识数组 a[0] = 0、a[1] = 1 等开始,然后使用自定义比较器/排序来获取索引数组。不需要太多额外空间,因为您只有一个额外的整数数组而不是另一个集合。
于 2008-10-16T01:32:55.127 回答