我确实有int对,即;(int,int)
1)给k个这样的对,检查它们是否唯一。也就是说,使用k对形成的集合的大小是k? 2)如果给定的k条记录是唯一的,则按排序顺序存储它们(按x存储,并按y解决冲突) 3)给定n组大小为k的集合,创建一组集。
要求1和2的例子
如果k=3
(100,100) (110,300) (120,200)是一个有效的集合并按排序顺序排列。 (100,100) (300,200) (200,300)是一个有效集合,但不按排序顺序排列。 (100,100) (100,200) (100,200)处于有效集合
要求3的例子
投入:
(100,100) (200,300) (100,100) (200,300) (100,100) (201,300) (300,200)
产出:
(100,100) (200,300) (100,100) (201,300) (300,200)
这是与我所面临的真正问题最接近的类比。我需要用java来完成这个任务,而且我从未在Java中工作过。我是一个中级c++程序员。
我可以通过一些丑陋的编码和排序来解决1和2。
然而,我无法得到3。下面是到目前为止我可以得到的3。
(poc代码)
import java.util.HashSet;
public class set {
public static void main (String []args) {
HashSet<Pair> s1 = new HashSet();
s1.add(new Pair(10,10));
s1.add(new Pair(10,10));
HashSet<Pair> s2 = new HashSet();
s2.add(new Pair(10,10));
s2.add(new Pair(10,10));
HashSet<HashSet<Pair>> s12 = new HashSet();
s12.add(s1);s12.add(s2);
for ( HashSet<Pair> hs : s12) {
for (Pair p : hs) {
System.out.println(""+ p.toString());
}
}
}
}发布于 2012-09-02 11:01:18
看起来您没有在结对类中重写equals和/或hashCode方法。
例如,如果您的Pair类具有以下结构:
protected K value1;
protected V value2; 您应该将equals和hashCode实现为(示例):
public boolean equals(Object obj) {
if (!(obj instanceof Pair))
return false;
Pair that = (Pair)obj;
boolean result = true;
if (this.getValue1() != null)
result = this.getValue1().equals(that.getValue1());
else if (that.getValue1() != null)
result = that.getValue1().equals(this.getValue1());
if (this.getValue2() != null)
result = result && this.getValue2().equals(that.getValue2());
else if (that.getValue2() != null)
result = result && that.getValue2().equals(this.getValue2());
return result;
}
public int hashCode() {
int result = value1 != null ? value1.hashCode() : 0;
result = 31 * result + (value2 != null ? value2.hashCode() : 0);
return result;
} https://stackoverflow.com/questions/12234639
复制相似问题