Pre Sized HashMap Static Factories
Allocate maps and sets sized for a known entry count with HashMap.newHashMap and HashSet.newHashSet so later puts generally add without resizing.
Code
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class PresizedMaps {
public static void main(String[] args) {
List<String> words = List.of("alpha", "beta", "gamma", "delta");
// JDK 19+ 静态工厂:按预期条目数建表,put 过程一般不再触发内部扩容
Map<String, Integer> lengths = HashMap.newHashMap(words.size());
for (String w : words) {
lengths.put(w, w.length());
}
// 经典手工换算:expected / 0.75 + 1,语义与新工厂一致
int expected = 200;
int classic = (int) (expected / 0.75f) + 1;
System.out.println("classic capacity for 200: " + classic);
Set<String> unique = HashSet.newHashSet(words.size());
unique.addAll(words);
System.out.println("lengths=" + lengths.size() + " unique=" + unique.size());
System.out.println("beta length=" + lengths.get("beta"));
}
}What the code does
Pre Sized HashMap Static Factories is built around the class PresizedMaps and the function main.
Iteration happens inside for (String w : words) — everything outside it runs once.
Watch out for
- Nothing to add to the project before running it.
Using it
Signature: public static void main(String[] args)
The lines that carry the logic
List<String> words = List.of("alpha", "beta", "gamma", "delta");
Map<String, Integer> lengths = HashMap.newHashMap(words.size());
Set<String> unique = HashSet.newHashSet(words.size());
Interactive Tools for This Topic
FAQ
- What does Pre Sized HashMap Static Factories print when run?
- Execute the whole file; each printed line is prefixed with a label like `classic capacity for 200:`, `lengths=`, `beta length=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.