Java
Associative Array
Java HashMap
Key-Value Pair
Java Collections

Java associative-array

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Java does not have a data structure called "associative array" in the same sense as languages like PHP or JavaScript, where an associative array equates to a native map or dictionary. However, Java provides similar functionality through its Map interface and its various implementations such as HashMap, TreeMap, and LinkedHashMap. These data structures allow us to store data in key-value pairs, which is essentially what an associative array is intended to do.

The Map Interface

In Java, the Map<K, V> interface is the closest equivalent to an associative array. This interface is part of the Java Collections Framework and offers key-value pair storage. Here's a look at the primary operations and methods associated with the Map interface:

  • put(K key, V value): Associates the specified value with the specified key.
  • get(Object key): Returns the value associated with the given key.
  • remove(Object key): Removes the mapping for the specified key if present.
  • containsKey(Object key): Returns true if the map contains a mapping for the specified key.
  • size(): Returns the number of key-value mappings.
  • isEmpty(): Returns true if the map contains no key-value mappings.

Implementations of the Map Interface

Java provides several implementations of Map, each with its unique characteristics:

HashMap

HashMap is one of the most commonly used implementations. It permits null keys and values and is efficient for most operations, provided uniform hashing; however, it does not guarantee any specific order of iteration.

java
1import java.util.HashMap;
2import java.util.Map;
3
4public class HashMapExample {
5    public static void main(String[] args) {
6        Map<String, Integer> ageMap = new HashMap<>();
7        ageMap.put("Alice", 30);
8        ageMap.put("Bob", 25);
9
10        System.out.println("Alice's age: " + ageMap.get("Alice"));
11    }
12}

TreeMap

TreeMap implements the NavigableMap interface and ensures that the entries are sorted according to the natural ordering of the keys or by a comparator provided at map creation time.

java
1import java.util.TreeMap;
2import java.util.Map;
3
4public class TreeMapExample {
5    public static void main(String[] args) {
6        Map<String, Integer> ageMap = new TreeMap<>();
7        ageMap.put("Alice", 30);
8        ageMap.put("Bob", 25);
9
10        System.out.println("Sorted ages: " + ageMap);
11    }
12}

LinkedHashMap

LinkedHashMap maintains a doubly-linked list running through all its entries, preserving the insertion order (or access order, if configured).

java
1import java.util.LinkedHashMap;
2import java.util.Map;
3
4public class LinkedHashMapExample {
5    public static void main(String[] args) {
6        Map<String, Integer> ageMap = new LinkedHashMap<>();
7        ageMap.put("Alice", 30);
8        ageMap.put("Bob", 25);
9
10        System.out.println("Insertion-order ages: " + ageMap);
11    }
12}

Table: Overview of Map Implementations

ImplementationOrderedAllows NullsSynchronization
HashMapNoYesNo
TreeMapYes (Sorted)No (for keys)No
LinkedHashMapYes (Insertion/Access)YesNo
ConcurrentHashMapNoNoYes

Additional Details

Synchronization

While Map implementations such as HashMap are not synchronized, ConcurrentHashMap provides a thread-safe alternative suitable for concurrent modifications. It is particularly useful in multithreaded environments where the map needs to be modified and accessed by multiple threads.

Performance Considerations

  • HashMap has constant-time performance for the basic operations like get and put, assuming the hash function disperses elements properly among the buckets.
  • TreeMap operations such as adding, removing, and accessing an entry have a time complexity of O(logn)O(\log n) due to the red-black tree implementation.
  • LinkedHashMap offers predictable iteration order and incurs a minor performance and memory overhead compared to HashMap.

Use Cases

  • HashMap is ideal for most general-purpose applications due to its performance characteristics.
  • TreeMap is useful when you need a sorted map or need to navigate through the map in a sorted order.
  • LinkedHashMap works well when you need to preserve the order of insertion, such as in caches.

By understanding these characteristics and use cases, developers can effectively choose the appropriate Map implementation that fits their specific requirements.

Conclusively, while Java does not directly use the term "associative array," the Map interface and its implementations provide equivalent functionality, offering flexibility and efficiency in managing key-value pairs.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.