Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java HashSet contains method return true when it supposes to be false

I define a Triple class with equals and hashcode method. According the docs,HashSet.contains() method of Java HashSet must returns the same value of Objects.equals(). But contains() method of Java HashSet method return true, when it suppose to be false.

class Triple{

    private List<Integer> triple;

    public Triple(int one, int two, int three){
        this.triple = new ArrayList<>();
        this.triple.add(one);
        this.triple.add(two);
        this.triple.add(three);
    }

    public int hashCode(){
        return triple.get(0).hashCode() + triple.get(1).hashCode() + triple.get(2).hashCode();
    }

    public boolean equals(Object t){
        Triple triple = (Triple)t;
        return triple.triple.contains(this.triple.get(0))
                && triple.triple.contains(this.triple.get(1))
                && triple.triple.contains(this.triple.get(2));
    }
}
public class Main {
    public static void main(String[] args) {
        HashSet<Triple> answersSet = new HashSet<>();
        Triple triple1 = new Triple(-4,0,4);
        Triple triple2 = new Triple(0,0,0);
        answersSet.add(triple1);
        boolean b = answersSet.contains(triple2); //returns true
        b = Objects.equals(triple1,triple2); //but it returns false, 
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your equals is broken. You only test if the value is contained in the List, not that the three values are equal. I think you wanted

@Override
public boolean equals(Object o) {
    Triple t = (Triple) o;
    return triple.get(0).equals(t.triple.get(0))
            && triple.get(1).equals(t.triple.get(1))
            && triple.get(2).equals(t.triple.get(2));
}

Which (obviously) returns false with your example data. Also, you can simplify your constructor

public Triple(int one, int two, int three) {
    this.triple = List.of(one, two, three);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading