如何有效地获得一组的所有对? [英] How to get all pairs of a set efficiently?

查看:35
本文介绍了如何有效地获得一组的所有对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个 Set 的对象,我想遍历它的所有(无序)对.

Given an object of a Set, I want to walk through all (unordered) pairs of it.

示例:Set = {1, 2, 3},对:(1, 2), (1, 3), (2, 3).

Example: Set = {1, 2, 3}, Pairs: (1, 2), (1, 3), (2, 3).

在处理Vector时,可以借助每个元素的索引来实现这一点:

When dealing with a Vector<Integer>, one can achieve this with help of the index of each element:

for (int i = 0; i < vector.size(); i++)
  for (int j = i + 1; j < vector.size(); j++)
    // Do something with vector.get(i) and vector.get(j)

但是 Set 中的元素没有索引.

But elements in a Set<Integer> have no indices.

到目前为止,我发现的最佳解决方案是将 Set 转换为 Vector 并使用上述解决方案.

The best solution, I found so far, is to convert the Set to a Vector and use the solution above.

有更有效/更直接的解决方案吗?

Is there a more efficient / direct solution ?

推荐答案

List<Integer> list = new ArrayList<Integer>(mySet);
for (int i = 0; i < list .size(); i++)
    for (int j = i + 1; j < list .size(); j++)
        // Do something with vector.get(i) and vector.get(j)

这篇关于如何有效地获得一组的所有对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆