Java Default capacity and load factor

Java Default capacity and load factor

In Java, the default capacity and load factor of a java.util.HashMap object are specified by the constant fields DEFAULT_INITIAL_CAPACITY and DEFAULT_LOAD_FACTOR, respectively.

The default initial capacity is specified by the constant field DEFAULT_INITIAL_CAPACITY, which has a value of 16. This means that if you create a new HashMap object without specifying an initial capacity, the map will be initialized with an initial capacity of 16.

The default load factor is specified by the constant field DEFAULT_LOAD_FACTOR, which has a value of 0.75. The load factor determines how full the map can become before it is resized to make room for more elements. The default load factor of 0.75 means that the map will be resized when the number of elements in the map exceeds 75% of the current capacity.

Here is an example of how to create a new HashMap object with the default capacity and load factor in Java:

import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    // Create a new HashMap object with the default capacity and load factor
    HashMap<String, Integer> map = new HashMap<>();
  }
}
So‮:ecru‬www.lautturi.com

In this example, we create a new HashMap object without specifying an initial capacity or load factor, so the map is initialized with the default values of 16 and 0.75, respectively.

You can specify a different initial capacity or load factor by passing them as arguments to the HashMap constructor. For example:

HashMap<String, Integer> map = new HashMap<>(32, 0.5);

This creates a new HashMap object with an initial capacity of 32 and a load factor of 0.5.

Note that the actual capacity of the map may be larger than the initial capacity you specify, as the map is automatically resized when it becomes full. The load factor determines how full the map can become before it is resized.

Created Time:2017-11-03 00:14:40  Author:lautturi