Hash code

6 views
Skip to first unread message

Praveen

unread,
Jul 16, 2009, 2:07:31 AM7/16/09
to Technical Discussion
Hi,

I have a program like -

public static void main(String[] args) {
for(int i = 0; i < 10; i++){
System.out.println(new Object().hashCode());
}
}

Suppose i got Out put like-

4384790
9634993
16417451
107720314
576877
126774
76332
633316
413875
59827574

that fine, every time a new object will be created and its hash code
is printted.
but when i run this program again, i got the same output !!!!!!

every time I got the same output.

WHY ?????????

Rajnish

unread,
Jul 16, 2009, 12:35:33 PM7/16/09
to Technical Discussion
Hi

I think that was due to local objects creation each time on same
memory space.
But I wonder when I test it as instance variable. I found more
confusing results.

I run two instances of JVM. Code is as under

JVM 1:
public class Test1 {
int i = 0;
static Test1 o[] = new Test1[10];

public static void main(String[] args) throws InterruptedException
{
Thread t = new Thread(){
public void run(){
for(int i = 0; i < 10; i++){
o[i] = new Test1();
System.out.println(o[i].hashCode());
o[i].i = i;
}
}
};
t.start();
Thread.sleep(8000);

for(int i = 0; i < 10; i++){
System.out.println(o[i].i);
}
}


JVM 2:
public class Test1 {
int i = 0;
static Test1 o[] = new Test1[10];

public static void main(String[] args) throws InterruptedException
{
Thread t = new Thread(){
public void run(){
for(int i = 0; i < 10; i++){
o[i] = new Test1();
System.out.println(o[i].hashCode());
}
}
};
t.start();
Thread.sleep(1000);

for(int i = 0; i < 10; i++){
System.out.println(o[i].i);
}
}



I run JVM 1 and then JVM 2.

Both the JVMs print same hashcode for objects, but values were
different.
If native hashcode has something to so with addresses then both JVMs
generated same addresses and they should have same values each time.?


Still trying to find the solution... ?

subhi

unread,
Jul 27, 2009, 10:37:37 AM7/27/09
to Technical Discussion
Hi Praveen
in second run you haven't mention
o[i].i = i;
inside the for loop , right ? I think thats why the values are coming
diff.

subhash.
> > WHY ?????????- Hide quoted text -
>
> - Show quoted text -
Reply all
Reply to author
Forward
0 new messages