There are two problems here.
equals must be lowercase and accept Object- You must also override
hashCode
The modified code may look as follows. Please note that the implementation is far from perfect, as equalsyou need to check the null value and whether type creation is possible. Also hashCode, this 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]
source
share