Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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