Skip to content

Instantly share code, notes, and snippets.

@melwinjose1991
Last active September 25, 2016 15:02
Show Gist options
  • Save melwinjose1991/bb721f9ef94074e1a18ab45f897aad5c to your computer and use it in GitHub Desktop.
Save melwinjose1991/bb721f9ef94074e1a18ab45f897aad5c to your computer and use it in GitHub Desktop.
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class LearningHashSet {
private static class Element {
int roll_no;
public Element(int r){
roll_no=r;
}
// hashCode() is used to find the bucket
@Override
public int hashCode() {
return roll_no%10;
}
// equals() is used to check if objects
// are equal
@Override
public boolean equals(Object obj) {
return roll_no==(((Element)obj).roll_no);
}
/*
The contract between equals() and hashCode() is:
- If two objects are equal, then they must have the same hash code.
- If two objects have the same hash code, they may or may not be equal.
NOTE : HashSet is backed by HashMap, so the Keys are the Elements
and values are all references to the SAME dummy objects.
Highlighted in the image
*/
/* Default equals()
public boolean equals(Object obj) {
// checks if obj are equal
return super.equals(obj);
}
*/
}
public static void main(String[] args) {
Set<Element> ts = new HashSet<Element>();
if(ts.add(new Element(1))) System.out.println("1 added");
// hashCode = 1, goes to bucket-1
if(ts.add(new Element(11))) System.out.println("11 added");
// hashCode = 1, goes to bucket-1
// Since the objects the different insertion is successful
if(ts.add(new Element(2))) System.out.println("2 added");
// hahsCode = 2, goes to bucket-2
Element three = new Element(3);
if(ts.add(three)) System.out.println("three added");
// hahsCode = 3, goes to bucket-3
if(ts.add(three)) System.out.println("three added");
// hahsCode = 3, goes to bucket-3
// but since the elements are equal(same roll-no), insertion fails
// Would also FAIL with the default equals(), as the same objects are used
if(ts.add(new Element(3))) System.out.println("three added");
// hahsCode = 3, goes to bucket-3
// but since the elements are equal(same roll-no), insertion fails
// Would PASS with the default equals(), as different objects are used
Iterator<Element> i = ts.iterator();
while(i.hasNext()){
Element current = i.next();
System.out.println(current.roll_no);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment