首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >集合集合中的唯一集

集合集合中的唯一集
EN

Stack Overflow用户
提问于 2012-09-02 08:59:38
回答 1查看 610关注 0票数 2

我确实有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代码)

代码语言:javascript
复制
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());
            }
        }
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-02 11:01:18

看起来您没有在结对类中重写equals和/或hashCode方法。

例如,如果您的Pair类具有以下结构:

代码语言:javascript
复制
protected K value1;
protected V value2; 

您应该将equalshashCode实现为(示例):

代码语言:javascript
复制
 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;
} 
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12234639

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档