dcsimg
adding objects with same hashcodes and true value return by equals() method to a set.
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Anonymous
Posted On:   Wednesday, April 27, 2011 04:44 AM

import java.util.HashSet; import java.util.Set; public class Test { public static void main(String[] args) { Set set=new HashSet (); set.add(new abc()); set.add(new abc()); set.add(new abc()); set.add(new abc()); System.out.println(set); } } class abc{ @Override public int hashCode() { // TODO Auto-generated method stub return 1; } @Override public boolean equals(Object obj) { // TODO Auto-generated method stub return true; } } when equals() returns false then output : [abc@1, abc@1, abc@1, abc@1] no problem with that. but when i run    More>>
			
import java.util.HashSet;
import java.util.Set;
public class Test {
public static void main(String[] args) {

Set set=new HashSet ();
set.add(new abc());
set.add(new abc());
set.add(new abc());
set.add(new abc());
System.out.println(set);
}
}
class abc{
@Override
public int hashCode() {
// TODO Auto-generated method stub
return 1;
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return true;
}
}


when equals() returns false then output :
[abc@1, abc@1, abc@1, abc@1] no problem with that.

but when i run above code gives output:
abc@1
which means it is not going to add any duplicate object to set as a set checks for hashcode first then equals method to test two objects equality.
but does it really adds one object or it makes a linked list out of these all objects.    <<Less

Re: adding objects with same hashcodes and true value return by equals() method to a set.

Posted By:   amitg  
Posted On:   Monday, August 6, 2012 08:39 PM

hi,

if you see it maintain a list of unique records. 


About | Sitemap | Contact