Skip to content

Instantly share code, notes, and snippets.

@tivrfoa
Forked from apangin/StringBuilderHash.java
Created June 9, 2021 12:38
Show Gist options
  • Save tivrfoa/691730c5128b9ddf58ccc40faab1e410 to your computer and use it in GitHub Desktop.
Save tivrfoa/691730c5128b9ddf58ccc40faab1e410 to your computer and use it in GitHub Desktop.
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
// See https://twitter.com/tagir_valeev/status/1402089474805354499
public class StringBuilderHash {
public static void main(String[] args) {
List<StringBuilder> list = IntStream.range(0, 10_000_000)
.mapToObj(i -> new StringBuilder(0))
.filter(s -> ((s.hashCode() ^ s.hashCode() >>> 16) & 0xfff) == 0)
.sorted(Comparator.comparingInt(Object::hashCode))
.collect(Collectors.toList());
StringBuilder sb = list.remove(IntStream.range(1, list.size())
.filter(i -> list.get(i).hashCode() == list.get(i - 1).hashCode())
.findFirst()
.orElseThrow());
Set<StringBuilder> set = new HashSet<>(list);
set.add(sb);
System.out.println(set.contains(sb));
sb.append("oops");
System.out.println(set.contains(sb));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment