View Single Post
  #1 (permalink)  
Old 08-02-2007, 11:44 AM
haridharna haridharna is offline
Member
 
Join Date: Aug 2007
Posts: 3
haridharna is on a distinguished road
how does the remove method work for sets and hashsets
Hello,
I am hari a resident of india.
I have been to this form many times. but this is my first posting.

I have a little confusion with the remove method of Set and HashSet.
Can any one tell me how does this method work exactly.
See the code and the result given below. I am confused aboud when the hashcode and the equals methods will be called.

Code:
import java.util.*; class KeyMaster { public int i; public KeyMaster(int i) { this.i = i; } public boolean equals(Object o) { System.out.println("equal:"+ (i == ((KeyMaster) o).i)); return i == ((KeyMaster) o).i; } public int hashCode() { System.out.println("Hashcode:"+i); return i; } public String toString() { return ""+i; } } public class MapIt { public static void main(String[] args) { Set<KeyMaster> set = new HashSet<KeyMaster>(); KeyMaster k1 = new KeyMaster(1); KeyMaster k2 = new KeyMaster(2); set.add(k1); set.add(k2); k1.i=2; set.remove(k1); System.out.println(set.contains(k2)); System.out.println(set); } }
The ouput for the above code is :
Hashcode:1
Hashcode:2
Hashcode:2
equal:true
Hashcode:2
false
[2]

Code:
public class MapIt { public static void main(String[] args) { Set<KeyMaster> set = new HashSet<KeyMaster>(); KeyMaster k1 = new KeyMaster(1); KeyMaster k2 = new KeyMaster(2); set.add(k1); set.add(k2); // k1.i=2; set.remove(k1); System.out.println(set.contains(k2)); System.out.println(set); } }
if we comment the k1.i=2 the following is the output.
Hashcode:1
Hashcode:2
Hashcode:1
Hashcode:2
true
[2]
---------------

Code:
public class MapIt { public static void main(String[] args) { Set<KeyMaster> set = new HashSet<KeyMaster>(); KeyMaster k1 = new KeyMaster(1); KeyMaster k2 = new KeyMaster(2); set.add(k1); set.add(k2); k1.i=2; set.remove(k1); System.out.println(set.contains(k1)); System.out.println(set.contains(k2)); System.out.println(set); } }
for the above code the following is the output:

Hashcode:1
Hashcode:2
Hashcode:2
equal:true
Hashcode:2
false
Hashcode:2
false
[2]

I am confused with when the equals method will be called and why the contains method is giving false.

Last edited by levent : 08-02-2007 at 12:11 PM. Reason: Codes are placed inside [code] tag.
Reply With Quote
Sponsored Links