Skip to content

Instantly share code, notes, and snippets.

@AlinaWithAFace
Created April 18, 2018 17:04
Show Gist options
  • Save AlinaWithAFace/46101d4fc24f8ad800ee74d651d54a88 to your computer and use it in GitHub Desktop.
Save AlinaWithAFace/46101d4fc24f8ad800ee74d651d54a88 to your computer and use it in GitHub Desktop.
Here's a small example where we override a hashset's equals and hashcode functiosn in order to determind uniqueness ourselves
import java.util.HashSet;
/**
* Assume two cows are the same if they have the same name.
* Write class Cow and the necessary methods to make main this work, and put a print statement inside each method.
* Then on the lines next to each call to add, write what the methods would print.
*/
class HashSetPractice {
/*
* On the comment lines provided, write *all* that is printed as a
* result of each line of code.
*/
public static void main(String[] args) {
HashSet<Cow> herd = new HashSet<Cow>();
herd.add(new Cow("A")); //Making cow A. Hashing cow A.
System.out.println();
herd.add(new Cow("Alba")); //Making cow Alba. Hashing cow Alba.
System.out.println();
herd.add(new Cow("A")); //Making cow A. Hashing cow A. Checking if cow A equals A.
System.out.println();
herd.add(new Cow("Aga")); //Making cow Aga. Hashing cow Aga.
System.out.println();
herd.add(new Cow("A")); //Making cow A. Hashing cow A. Checking if cow A equals A.
System.out.println();
System.out.println(herd.size()); //3
}
}
class Cow {
String name;
Cow(String name) {
System.out.printf("Making cow %s. ", name);
this.name = name;
}
@Override
public int hashCode() {
System.out.printf("Hashing cow %s. ", name);
return this.name.hashCode();
}
@Override
public boolean equals(Object object) {
if (object instanceof Cow) {
Cow cow = (Cow) object;
System.out.printf("Checking if cow %s equals %s. ", this.name, cow.name);
return this.name.equals(cow.name);
} else {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment