DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Migrate, Modernize and Build Java Web Apps on Azure: This live workshop will cover methods to enhance Java application development workflow.

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Kubernetes in the Enterprise: The latest expert insights on scaling, serverless, Kubernetes-powered AI, cluster security, FinOps, and more.

E-Commerce Development Essentials: Considering starting or working on an e-commerce business? Learn how to create a backend that scales.

Related

  • Java 11 to 21: A Visual Guide for Seamless Migration
  • Quarkus 3: The Future of Java Microservices With Virtual Threads and Beyond
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • Reading an HTML File, Parsing It and Converting It to a PDF File With the Pdfbox Library

Trending

  • Apply Strangler Pattern To Decompose Legacy System Into Microservices: Part 1
  • JPA Criteria With Pagination
  • Demystifying Databases, Data Warehouses, Data Lakes, and Data Lake Houses
  • Legacy App Migration: How Discovery Phase Speeds up Project Delivery
  1. DZone
  2. Coding
  3. Java
  4. WeakHashMap in Java With Class Example

WeakHashMap in Java With Class Example

Let's take a closer look at the WeakHashMap implementation in Java.

Ramesh Fadatare user avatar by
Ramesh Fadatare
·
Dec. 07, 18 · Presentation
Like (15)
Save
Tweet
Share
20.4K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we will learn WeakHashMap class from the java.util package with examples.

What Will We Learn?

  1. WeakHashMap Class Overview
  2. WeakHashMap Class Constructor Summary
  3. WeakHashMap Class Constructor Methods
  4. WeakHashMap Class Example

1. WeakHashMap Class Overview

WeakHashMap is a Hash table-based implementation of the Map interface with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. Both null values and the null key are supported. This class has performance characteristics similar to those of the HashMap class and has the same efficiency parameters of initial capacity and load factor. Like most collection classes, this class is not synchronized. A synchronized WeakHashMap may be constructed using the  Collections.synchronizedMap method. Weak Reference − if the only references to an object are weak references, the garbage collector can reclaim the object's memory at any time. It doesn't have to wait until the system runs out of memory. Usually, it will be freed the next time the garbage collector runs. This class is a member of the Java Collections Framework.

2. WeakHashMap Class Constructors

  • WeakHashMap() — Constructs a new, empty WeakHashMap with the default initial capacity (16) and load factor (0.75).
  • WeakHashMap(int initialCapacity) — Constructs a new, empty WeakHashMap with the given initial capacity and the default load factor (0.75).
  •  WeakHashMap(int initialCapacity, float loadFactor) — Constructs a new, empty WeakHashMap with the given initial capacity and the given load factor.
  • WeakHashMap(Map< ?extends K,? extends V> m)  — Constructs a new WeakHashMap with the same mappings as the specified map.

3. WeakHashMap Class Methods

  •  void clear() — Removes all of the mappings from this map.
  • boolean containsKey(Object key) — Returns true if this map contains a mapping for the specified key.
  •  boolean containsValue(Object value) — Returns true if this map maps one or more keys to the specified value.
  •  Set<  Map.Entry<K,V>>entrySet()  — Returns a Set view of the mappings contained in this map.
  • void forEach(BiConsumer<? super K,? super V> action)  — Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
  •  V get(Object key) — Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
  • boolean isEmpty() — Returns true if this map contains no key-value mappings.
  •  Set keySet() — Returns a Set view of the keys contained in this map.
  • V put(K key, V value)  — Associates the specified value with the specified key in this map.
  •  void putAll(Map<? extends K,? extends V> m) — Copies all of the mappings from the specified map to this map.
  •  V remove(Object key) — Removes the mapping for a key from this weak hash map if it is present.
  •  void replaceAll(BiFunction<? super K,? super V,? extends V>function)  — Replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
  •  int size() — Returns the number of key-value mappings in this map.
  • Collection values() — Returns a Collection view of the values contained in this map.

4. WeakHashMap Class Example

As we know, an entry in a WeakHashMapwill automatically be removed when its key is no longer externally referenced and the key is due for garbage collection. In this example, we created two keys — key1 and key2 — with values "ACTIVE" and "INACTIVE." Now, make key1 null and run the program. The output should be a single entry:

import java.util.Map;
import java.util.Map.Entry;
import java.util.WeakHashMap;

public class WeakHashMapExample {
    public static void main(final String[] args) {
        final Map<Key, Project> map = new WeakHashMap<>();
        Key key1 = new Key("ACTIVE");
        final Key key2 = new Key("INACTIVE");
        map.put(key1, new Project(100, "Customer Management System", "Customer Management System"));
        map.put(key2, new Project(200, "Employee Management System", "Employee Management System"));

        key1 = null;
        System.gc();
        for (final Entry<Key, Project> entry : map.entrySet()) {
            System.out.println(entry.getKey().getKey() + "   " + entry.getValue());
        }
    }
}

class Key {
    private String key;

    public Key(final String key) {
        super();
        this.key = key;
    }

    public String getKey() {
        return key;
    }

    public void setKey(final String key) {
        this.key = key;
    }
}


Output:

INACTIVE   [project id : 200, project name : Employee Management System, 
           project desc : Employee Management System ]


Note that the key1 is null and its entry is removed and garbage collected. Happy coding!

Further Learning

Collections Framework - EnumMap
Collections Framework - IdentityHashMap

Collections Framework - CopyOnWriteArraySet
Collections Framework - EnumSet

Collections Framework - CopyOnWriteArrayList

Reference

https://docs.oracle.com/javase/8/docs/api/java/util/WeakHashMap.html

Java (programming language)

Published at DZone with permission of Ramesh Fadatare. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Java 11 to 21: A Visual Guide for Seamless Migration
  • Quarkus 3: The Future of Java Microservices With Virtual Threads and Beyond
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • Reading an HTML File, Parsing It and Converting It to a PDF File With the Pdfbox Library

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: