DEV Community

Mohammed Riyas
Mohammed Riyas

Posted on

learn usage about Hashcode and equals in JAVA

hashCode in Java is a function that returns the hashcode value of an object on calling.

import java.util.*;
public class HashCodes {
String name;
int id;

    public HashCodes(String name, int id) {
        this.name = name;
        this.id = id;
    }


    public static void main(String[] args) {
        HashCodes h=new HashCodes("ali",101);
        HashCodes h1=new HashCodes("al",101);
      Set s=new HashSet();
      s.add(h);
      s.add(h1);
        System.out.println(s);
    }

    @Override
    public String toString() {
        return "HashCodes{" + "name=" + name + ", id=" + id + '}';
    }

    @Override
    public int hashCode() {
        int hash = 7;
     //   hash = 83 * hash + Objects.hashCode(this.name);
        hash = 83 * hash + this.id;
        return hash;
    }

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

}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)