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
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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Trending

  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Contextual AI Integration for Agile Product Teams
  • How to Format Articles for DZone
  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  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.

By 
Ramesh Fadatare user avatar
Ramesh Fadatare
·
Dec. 07, 18 · Presentation
Likes (15)
Comment
Save
Tweet
Share
20.8K 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

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • 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: