*Please help* JAVA: Need help in storing a Pair in a set

So I’m trying to learn java. I’m kinda comfortable with it now but when faced with a problem where i need to store a pair in a set (which can be done easily in c++), I’m unable to do it.

Here’s what I tried. Please help, I spent days doing this problem trying to find the mistake only to realize set was not working :face_with_head_bandage:

Here’s the Pair class:

class Pair<U, V>{
	public final U first;
	public final V second; 

	private Pair(U first, V second){
		this.first = first;
		this.second = second;
	}
	public static <U, V> Pair <U, V> of(U a, V b){
		return new Pair<>(a, b);
	}
}

Here’s the main function:

public static void main(String []args){
        HashSet<Pair<Integer,Integer>> map = new HashSet<Pair<Integer,Integer>>();
        map.add(Pair.of(4,-3));
        if(!map.contains(Pair.of(4,-3)))
            System.out.println("I'm dumb af"); //it prints
}

Would be great if someone told me an elegant way(or literally any way) to do this

The reason your code is not working is because you are trying to match two identical objects and not two equal object. There is thin line of difference between them because when you say two objects are equal you say that both of them have the same reference and when you say two objects are identical means their variables have same value. Try to draw an analogy with why we need equals method in string and “==” doesn’t work out.

Your code can work in both the way:

  1. Override the hashcode and equals method in Pair class. Below is how Pair class should look like:

    class Pair<U, V>{
    public final U first;
    public final V second;

    public Pair(U first, V second){
    this.first = first;
    this.second = second;
    }
    public static <U, V> Pair <U, V> of(U a, V b){
    return new Pair<>(a, b);
    }

    final int a = 2;

    @Override
    public int hashCode() {
    int hash = 5;
    hash = 17 * hash + this.a;
    return hash;
    }

    @Override
    public boolean equals(Object obj) {
    if (obj == null) {
    return false;
    }
    if (getClass() != obj.getClass()) {
    return false;
    }
    final Pair other = (Pair) obj;
    if (this.a != other.a) {
    return false;
    }
    return true;
    }
    }

  2. Making the objects equal instead of identical. Below is how main method should look like:

     HashSet<Pair<Integer,Integer>> map = new HashSet<Pair<Integer,Integer>>();
     Pair new1 = new Pair(4,-3);     //create new object
     map.add(new1);                               //same object added in set
     if(!map.contains(new1)){                //same object is checked in set
         System.out.println("I'm dumb af"); 
     }else{
         System.out.println("I'm not dumb af"); //it prints
     }
    

But this solution doesn’t make sense in practical solutions

Hope this helps.

1 Like

Thanks man!