Java ArrayList IndexOf - Finding Object Index

后端 未结 4 1384
独厮守ぢ
独厮守ぢ 2020-12-05 19:56

Lets say I have a class

public class Data{
    public int k;
    public int l;
    public Data(int k, int l){
      this.k = k; 
      this.l = l;
    }
             


        
4条回答
  •  鱼传尺愫
    2020-12-05 20:25

    The signature of your equals method is wrong. You are not overriding the equals in Object, but just overloading it.

    To override the behavior of equals method in Object, your signature must exactly match with the one in Object. Try this:

    public boolean equals(Object o) {
        if(!(o instanceof Data)) return false;
        Data other = (Data) o;
        return (this.k == other.k && this.l == other.l);
    }
    

    In addition, as others suggested, it is a good idea to override hashCode method also for your object to work correctly in map based collections.

提交回复
热议问题