Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Explain res = id^(id >>> 32), please

Hullo!
I have this code

public int hashCode(){
        int res = (int) (id ^ (id >>> 32));
        res = 31 * res + (name != null ? name.hashCode() : 0);
        return res;
    }

And this is my equals code

    public boolean equals(Object o) {
        // object ref identical or not
        if (this == o) return true;
        if (o == null) return false;
        //class identical?
        if (getClass() != o.getClass()) return false;
        Person person = (Person) o;

        if(id != person.id) return false;

        return Objects.equals(name, person.name);
    }

I don`t understand operations over result.
Why do we have to do these operations?
Will be very grateful if someone can explain it to me

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Equals i understand well, but i read they are connected somehow, so I’ve attached the comparison code just in case

>Solution :

Explain res = id^(id >>> 32) please

  • id >>> n for an int, shifts id right n%32 bits without extending the negative sign bit if one is present. So (id >>> 32) is effectively == id.
  • ^ is an exclusive OR which says for any bit a and b, a^b == 1 if a and b are different otherwise they a^b == 0. E.g. 1^1 == 0. 0^0 == 0, 1^0 == 1

So id ^ id == 0.

if id is a long, (id >>> 32) shifts the high order 32 bits of that long right 32 bits and then exclusive ors the original long with that value.

The over all computation of hashCode is to use that technique sometimes employed with others to generate a number for use in data structures that are used to index by hashcode. in Java, primary examples are Maps and Sets.

Here is a demo.

long v = Long.MIN_VALUE; // has 1 in hob (high order bit) and rest is 0's
System.out.println(Long.toBinaryString(v));
 
long result = v ^ (v >>> 32); // now hob should be 1 and hob of low order int should be 1

System.out.println(Long.toBinaryString(result));
1000000000000000000000000000000000000000000000000000000000000000
1000000000000000000000000000000010000000000000000000000000000000
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading