【问题标题】:Unique values of custom class in Java SetJava Set 中自定义类的唯一值
【发布时间】:2016-07-05 15:46:01
【问题描述】:

我希望我的Set 中只有 2 个元素,但我在打印时收到了 3 个元素!如何定义唯一性?

public class test {

    public static void main(String[] args) {

        class bin {
            int a;
            int b;
            bin (int a, int b){
                this.a=a;
                this.b=b;
            }
            public boolean Equals(bin me) {
                if(this.a==me.a && this.b==me.b)
                    return true;
                else 
                    return false;
            }   
            @Override
            public String toString() {
                return a+" "+b;
            }
        }

        Set<bin> q= new HashSet<bin>();
        q.add(new bin(11,23));
        q.add(new bin(11,23));
        q.add(new bin(44,25));

        System.out.println(q);
    }
}

【问题讨论】:

  • 您在打印之前从未测试过唯一性

标签: java set hashset


【解决方案1】:

这里有两个问题

  • equals 应为小写并接受 Object
  • 您还必须覆盖 hashCode

修改后的代码如下所示。请注意,实现远非完美,因为在equals 中,您应该检查 null 以及是否可以进行类型转换等。@ 987654325@ 只是一个示例,但如何实现这些事情是另一个主题。

import java.util.Set;
import java.util.HashSet;

public class test {

    public static void main(String[] args) {

        class bin{
            int a;
            int b;
            bin (int a, int b){
                this.a=a;
                this.b=b;
            }

            @Override
            public boolean equals(Object me) {
                bin binMe = (bin)me;
                if(this.a==binMe.a && this.b==binMe.b)
                    return true;
                else 
                    return false;
            }   

            @Override
            public int hashCode() {
                return this.a + this.b;
            }

            @Override
            public String toString() {
                return a+" "+b;
            }
        }

        Set<bin> q= new HashSet<bin>();
        q.add(new bin(11,24));
        q.add(new bin(11,24));
        q.add(new bin(10,25));
        q.add(new bin(44,25));

        System.out.println(q);
    }
}

结果:

[11 24, 10 25, 44 25]

【讨论】:

    猜你喜欢
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多