Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

java - Why hashCode() returns the same value for a object in all consecutive executions?

I am trying some code around object equality in java. As I have read somewhere

hashCode() is a number which is generated by applying the hash function. Hash Function can be different for each object but can also be same. At the object level, it returns the memory address of the object.

Now, I have sample program, which I run 10 times, consecutively. Every time i run the program I get the same value as hash code.

If hashCode() function returns the memory location for the object, how come the java(JVM) store the object at same memory address in the consecutive runs?

Can you please give me some insight and your view over this issue?

The Program I am running to test this behavior is below :

public class EqualityIndex {

    private int index;

    public EqualityIndex(int initialIndex) {
       this.index = initialIndex;
    }

    public static void main(String[] args) {
        EqualityIndex ei = new EqualityIndex(2);
        System.out.println(ei.hashCode());
    }

}

Every time I run this program the hash code value returned is 4072869.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

how come the java(JVM) store the object at same memory address in the consecutive runs?

Why wouldn't it? Non-kernel programs never work with absolute memory addresses, they use virtual memory where each process gets its own address space. So it's no surprise at all that a deterministic program would place stuff at the same location in each run.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...