Skip to content

Instantly share code, notes, and snippets.

@amaembo
Created June 9, 2021 06:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amaembo/e20a66bce72b2e937bbfaa4dd2df1b29 to your computer and use it in GitHub Desktop.
Save amaembo/e20a66bce72b2e937bbfaa4dd2df1b29 to your computer and use it in GitHub Desktop.
import java.util.*;
import java.util.stream.*;
public class StringBuilderInHashMap {
public static void main(String[] args) {
List<StringBuilder> list = Stream.generate(() -> {
while (true) {
StringBuilder sb = new StringBuilder("a");
int hc = sb.hashCode();
if (((hc ^ (hc >>> 16)) & 0x3F) == 0) {
return sb;
}
}
}).limit(40)
.sorted(Comparator.comparingInt(Object::hashCode))
.toList();
StringBuilder sb = Stream.generate(StringBuilder::new)
.dropWhile(b -> Collections.binarySearch(list, b,
Comparator.comparingInt(Object::hashCode)) < 0)
.findFirst().get();
Set<StringBuilder> set = new HashSet<>(list);
set.add(sb);
System.out.println(set.contains(sb)); // prints "true"
sb.append("oops");
System.out.println(set.contains(sb)); // prints "false"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment