我有TreeSet包含客户对象.它包含10个圆形对象.我想在集合上运行两个循环,以便我可以将每个元素与下面的所有元素进行比较.这是我可以做的例子List,但我不知道如何做到这一点Set
for (int i = 0; i < set.size(); i++) {
// Circle circle = set.get(i);
for (int j = i+1; i < set.size(); j++) {
// Circle circle = set.get(j);
}
}
Run Code Online (Sandbox Code Playgroud)
我可以做到这一点 List<String> list=new ArrayList<>(set),我可以实现两个排序(通过设置)和在列表上运行两个循环,但它将是额外的内存.
我想要实现的目标: -
对于外循环中的每个圆(按半径按降序排序),我想计算内循环中每个圆的面积(如果该圆是有效的(请假设圆形对象中有一个属性,告诉它是否有效) .如果有效,我需要计算外循环和内循环中的圆区域的乘法,并找到最大结果
使用foreach:
for (Customer customer : set ) {
for (Customer otherCustomer : set ) {
// do your processing
}
}
Run Code Online (Sandbox Code Playgroud)
您无法Set使用get(int index)特定于List接口的方法从a中检索元素.
对不起,我没注意你的内循环条件:
for (int j = i+1; i < set.size(); j++) {
Run Code Online (Sandbox Code Playgroud)
你确实希望内部循环在外部循环的当前元素之后开始.您可以TreeSet通过使用类声明您的集合并使用以下tailSet()方法来实现:
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if {@code fromElement} is null and
* this set uses natural ordering, or its comparator does
* not permit null elements
* @throws IllegalArgumentException {@inheritDoc}
* @since 1.6
*/
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
return new TreeSet<>(m.tailMap(fromElement, inclusive));
}
Run Code Online (Sandbox Code Playgroud)
所以你可以在外部循环的当前元素之后启动第二个循环:
TreeSet<Customer> set = new TreeSet();
for (Customer customer : set) {
for (Customer otherCustomer : set.tailSet(customer, false) {
// do your processing
System.out.println("");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
113 次 |
| 最近记录: |