Skip to content

Instantly share code, notes, and snippets.

@aidan-harding
Last active January 29, 2018 20:03
Show Gist options
  • Save aidan-harding/3c6a852e12943014ddf08b999f6f8df7 to your computer and use it in GitHub Desktop.
Save aidan-harding/3c6a852e12943014ddf08b999f6f8df7 to your computer and use it in GitHub Desktop.
Strange Set Behaviour in Apex
Integer nCallsToEquals = 0;
public class HashingTest {
private String s;
public HashingTest(HashingTest ht) {
this.s = ht.s;
}
public HashingTest(String s) {
this.s = s;
}
public Integer hashCode() {
return s.hashCode();
}
public Boolean equals(Object o) {
++nCallsToEquals;
if(o instanceof HashingTest) {
return s == ((HashingTest)o).s;
} else {
return false;
}
}
}
HashingTest k1 = new HashingTest('a');
HashingTest k2 = new HashingTest('b');
System.debug('k1.hashCode(): ' + k1.hashCode());
System.debug('k2.hashCode(): ' + k2.hashCode());
Set<HashingTest> aSet = new Set<HashingTest>();
aSet.add(k1);
aSet.add(k2);
nCallsToEquals = 0;
aSet.contains(k1);
System.debug('nCallsToEquals: ' + nCallsToEquals);
System.assertEquals(1, nCallsToEquals);
nCallsToEquals = 0;
aSet.contains(k2);
System.debug('nCallsToEquals: ' + nCallsToEquals);
System.assertEquals(1, nCallsToEquals);
// Comment out this debug line to get expected number of calls to equals()
System.debug('aSet: ' + aSet);
nCallsToEquals = 0;
aSet.contains(k1);
System.debug('nCallsToEquals: ' + nCallsToEquals);
System.assertEquals(1, nCallsToEquals);
nCallsToEquals = 0;
aSet.contains(k2);
System.debug('nCallsToEquals: ' + nCallsToEquals);
System.assertEquals(1, nCallsToEquals);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment