A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/java/util/java_util_weakhashmap.htm below:

Java WeakHashMap Class

Java WeakHashMap Class Introduction

The Java WeakHashMap class is a hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed by the garbage collector, when its key is no longer in use. Following are the important points about WeakHashMap −

Class declaration

Following is the declaration for java.util.WeakHashMap class −

public class WeakHashMap<K,V> 
   extends AbstractMap<K,V>
   implements Map<K,V>

Here <K> is the type of keys maintained by this map and <V> is the type of mapped values.

Class constructors Sr.No. Constructor & Description 1

WeakHashMap()

This constructor is used to create an empty WeakHashMap with the default initial capacity (16) and load factor (0.75).

2

WeakHashMap(int initialCapacity)

This constructor is used to create an empty WeakHashMap with the given initial capacity and the default load factor (0.75).

3

WeakHashMap(int initialCapacity, float loadFactor)

This constructor is used to create an empty WeakHashMap with the given initial capacity and the given load factor.

4

WeakHashMap(Map<? extends K,? extends V> m)

This constructor is used to create a new WeakHashMap with the same mappings as the specified map.

Class methods Methods inherited

This class inherits methods from the following classes −

Adding a Key-Value Pair to a WeakHashMap of Integer, Integer Pairs Example

The following example shows the usage of Java WeakHashMap put() method to put few values in a Map. We've created a Map object of Integer,Integer pairs. Then few entries are added using put() method and then map is printed.

package com.tutorialspoint;

import java.util.WeakHashMap;

public class WeakHashMapDemo {
   public static void main(String args[]) {
      
      // create hash map
      WeakHashMap<Integer,Integer> newmap = new WeakHashMap<>();

      // populate hash map
      newmap.put(1, 1);
      newmap.put(2, 2);
      newmap.put(3, 3); 

      System.out.println("Map elements: " + newmap);
   }
}
Output

Let us compile and run the above program, this will produce the following result.

Map elements: {3=3, 2=2, 1=1}

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4