Java Set中定制类的唯一值 [英] Unique values of custom class in Java Set

查看:145
本文介绍了Java Set中定制类的唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I expect to have only 2 elements in my Set but I receive 3 elements while printing! How can I define uniqueness?

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

推荐答案

这里有两个问题

  • equals应该为小写并接受Object
  • 您还必须覆盖hashCode
  • equals should be lowercase and accept an Object
  • You have to override hashCode as well

修改后的代码如下所示.请注意,实现远非完美,如equals一样,您应检查是否为null以及是否可以进行类型转换等.hashCode仅仅是示例,但如何实现此类事情是另一个主题.

The modified code could look like below. Note that the implementation is far from being perfect as in equals you should check for null and whether a type cast is possible etc. Also hashCode is just an example but how to implement such things is another topic.

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


结果:


Result:

[11 24,10 25,44 25]

[11 24, 10 25, 44 25]

这篇关于Java Set中定制类的唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆