程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

集合集合中的唯一集合

发布于2022-01-09 21:47     阅读(1143)     评论(0)     点赞(28)     收藏(5)


我确实有int对,即;(整数,整数)

1) 给定 k 个这样的对,检查它们是否唯一。IE; 使用 k 对形成的集合的大小是 k ?
2) 如果给定的 k 条记录是唯一的,则按排序顺序存储它们(按 x 并按 y 解决冲突)
3) 给定 n 个大小为 k 的集合,创建一组集合。


如果 k = 3 ,则要求 1 和 2 的示例

(100, 100) (110, 300) (120, 200) 是一个有效的集合并按顺序排列。
(100, 100) (300, 200) (200, 300) 是一个有效的集合,但没有排序。
(100, 100) (100, 200) (100, 200) 在有效集合中

要求 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。类对实现了可比性

(验证码)

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; 

你应该实现equalshashCodeas(example) :

 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;
} 


所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.javaheidong.com/blog/article/375984/fe67823673ab7d6b0c58/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

28 0
收藏该文
已收藏

评论内容:(最多支持255个字符)