Map<String, Object> result = new HashMap<String,Object>();

Copy the code

Maps.newhashmap (), which is provided by Google’s Guava.jar, is intended to simplify the code without requiring you to write generics by hand. It’s pretty handy, the code looks pretty clean, and there are security issues, because it’s essentially a HashMap() that’s returned to you, so the security aspect is the same as a HashMap

Map<String, Object> result = Maps.newHashMap();Copy the code

NewHashMap () the source code:

/**
   * Creates a <i>mutable</i>, empty {@code HashMap} instance.
   *
   * <p><b>Note:</b> if mutability is not required, use {@link
   * ImmutableMap#of()} instead.
   *
   * <p><b>Note:</b> if {@code K} is an {@code enum} type, use {@link
   * #newEnumMap} instead.
   *
   * @return a new, empty {@code HashMap}
   */
  public static <K, V> HashMap<K, V> newHashMap(a) {
    return new HashMap<K, V>();
  }Copy the code

3, Maps. NewHashMapWithExpectedSize (10) need to set the default element number when the instance is created,

Source code analysis:

We calculate the expectedSize + expectedSize /3 to expectedSize 10+ expectedSize /3 = 13. After calculation, it is set to 13, that is, the expectedSize /3 is increased by 1/3.

When the internal hash table maintained by a HashMap reaches 75% capacity (by default), rehash is triggered, and the process of rehash can be time consuming. Therefore, if the initial capacity is set to expectedSize + expectedSize / 3, the collision and error can be effectively reduced.

So, I can assume that setting the default size to expectedSize + expectedSize / 3 is a relatively good choice for performance when we know exactly how many elements are in the HashMap, but it also costs some memory.

 public static <K, V> HashMap<K, V> newHashMapWithExpectedSize(
      int expectedSize) {
    return new HashMap<K, V>(capacity(expectedSize));
  }
 
 
/** * Returns a capacity that is sufficient to keep the map from being resized as * long as it grows no larger than ExpectedSize and the load factor is >= its * default (0.75). */
  static int capacity(int expectedSize) {
    if (expectedSize < 3) {
      checkNonnegative(expectedSize, "expectedSize");
      return expectedSize + 1;
    }
    if (expectedSize < Ints.MAX_POWER_OF_TWO) {
      return expectedSize + expectedSize / 3;
    }
    return Integer.MAX_VALUE; // any large value
  }Copy the code

None of these maps are thread-safe because they are essentially hashMaps. If you want thread-safe, use ConcurrentMap. This is thread-safe. It has a flag bit in it that the current thread needs to get hold of before it can rehash. Basically, it has a lock in it, which is a thread issue