Java HashMap get works but containsKey does not

后端 未结 9 1284
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 05:41

I am trying to locate a key in a HashMap. I can print the selected key by using \'get\' but when I use \'containsKey\' in an if statement, it is not found.

I KNOW

9条回答
  •  醉梦人生
    2020-12-06 06:19

    i think sometime you need the hash code and sometimes not so i think in this way you can turn of the hash code checking when you want buy changing the hash code for all objects you want to 0

    public class sample(){
        @JsonIgnore
        private int hashCode = super.hashCode();
    
        public void setHashCode(int hashCode){
            this.hashCode = hashCode;
        }    
    
        @Override
        public int hashCode(){
            return this.hashCode;
        }    
    
        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final ReflectObject other = (ReflectObject) obj;
            if (this.hashCode != other.hashCode) {
                return false;
            }
            return true;
        }
    }
    

提交回复
热议问题