Hash-based collections with known capacity should be initialized with the proper related static method.
When creating an instance of HashMap or HashSet, the developer can pick a constructor with known capacity. However, the requested capacity is not fully allocated by default. Indeed, when the collection reaches the load factor of the collection (default: 0.75), the collection is resized on the fly, leading to unexpected performance issues.
As of Java 19, hash-based collections provide a static method that allocates the requested capacity at construction time.
private static final int KNOWN_CAPACITY = 1_000_000;
public static Map<String, Integer> buildAMap() {
return new HashMap<>(KNOWN_CAPACITY); // Noncompliant
}
public static Set<String> buildASet() {
return new HashSet<>(KNOWN_CAPACITY); // Noncompliant
}
private static final int KNOWN_CAPACITY = 1_000_000;
public static Map<String, Integer> buildABetterMap() {
return HashMap.newHashMap(KNOWN_CAPACITY);
}
public static Set<String> buildABetterSet() {
return HashSet.newHashSet(KNOWN_CAPACITY);
}
public static Set<String> buildABetterSet(float customLoadFactor) {
return new HashSet<>(KNOWN_CAPACITY, customLoadFactor);
}
Message:
Replace this call to the constructor with the better suited static method.
Highlighting:
The infringing constructor call.