64 lines
2.1 KiB
Plaintext
64 lines
2.1 KiB
Plaintext
Hash-based collections with known capacity should be initialized with the proper related static method.
|
|
|
|
== Why is this an issue?
|
|
|
|
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.
|
|
|
|
== How to fix it
|
|
|
|
As of Java 19, hash-based collections provide a static method that allocates the requested capacity at construction time.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java]
|
|
----
|
|
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
|
|
}
|
|
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java]
|
|
----
|
|
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);
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
- https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/util/HashMap.html#newHashMap(int)
|
|
- https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/util/HashSet.html#newHashSet(int)
|
|
- https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/util/LinkedHashMap.html#newLinkedHashMap(int)
|
|
- https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/util/LinkedHashSet.html#newLinkedHashSet(int)
|
|
- https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/util/WeakHashMap.html#newWeakHashMap(int)
|
|
|
|
|
|
Message: +
|
|
Replace this call to the constructor with the better suited static method.
|
|
|
|
Highlighting: +
|
|
The infringing constructor call. |