我确实有 int
对,即; (整数,整数)
1) Given k such pairs, check if they are unique. i.e; size of the Set formed using k pairs is k ?
2) if the given k records are unique then store them in sorted order ( by x and resolve conflict by y)
3) Given n such sets of size k, create a set of sets.
要求 1 和 2 的示例
如果 k = 3
(100, 100) (110, 300) (120, 200) is a valid set and in sorted order.
(100, 100) (300, 200) (200, 300) is a valid set but not in sorted order.
(100, 100) (100, 200) (100, 200) is in valid set
要求 3 的示例
输入:
(100, 100) (200, 300) (300, 200)
(100, 100) (200, 300) (300, 200)
(100, 100) (201, 300) (300, 200)
输出:
(100, 100) (200, 300) (300, 200)
(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());
}
}
}
}
最佳答案
看起来您没有重写 Pair 类中的 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;
}
关于java - 集合中的独特集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12234639/