Unique values of custom class in Java Set

ⅰ亾dé卋堺 提交于 2019-12-12 10:49:29

问题


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

回答1:


There are two issues here

  • equals should be lowercase and accept an Object
  • You have to override hashCode as well

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]



来源:https://stackoverflow.com/questions/38207632/unique-values-of-custom-class-in-java-set

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!