杰瑞科技汇

Java中Dictionary类怎么用?

Of course! In Java, the term "dictionary" is not a specific class name. Instead, it refers to a general concept of a data structure that stores key-value pairs. The primary and most common interface used for this purpose in Java is the java.util.Map.

Java中Dictionary类怎么用?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide to dictionaries (Maps) in Java.


The Core Concept: Map Interface

A Map is an object that maps keys to values. It cannot contain duplicate keys; each key can map to at most one value. You can retrieve a value by its key very quickly.

Key Characteristics:

  • Key-Value Pairs: Data is stored as pairs.
  • Unique Keys: Each key in a map must be unique.
  • Fast Lookups: Retrieving a value by its key is a very fast operation (average O(1) time complexity).

The Most Common Implementation: HashMap

HashMap is the workhorse of Java dictionaries. It provides the best performance for most use cases by using a hash table (or hash map) for storage.

Java中Dictionary类怎么用?-图2
(图片来源网络,侵删)

Key Features of HashMap:

  • Fast: Offers constant time complexity, O(1), for basic operations like put() and get() on average.
  • Unordered: It does not guarantee any specific order of the elements. The order can change over time as you add or remove elements.
  • Allows one null key and multiple null values.

How to Use HashMap: A Complete Example

import java.util.HashMap;
import java.util.Map;
public class JavaDictionaryExample {
    public static void main(String[] args) {
        // 1. Create a HashMap (our dictionary)
        // Syntax: Map<KeyType, ValueType> mapName = new HashMap<>();
        Map<String, Integer> studentAges = new HashMap<>();
        // 2. Add key-value pairs using the put() method
        studentAges.put("Alice", 21);
        studentAges.put("Bob", 22);
        studentAges.put("Charlie", 20);
        System.out.println("Initial Dictionary: " + studentAges);
        // Output: Initial Dictionary: {Charlie=20, Alice=21, Bob=22} (order may vary)
        // 3. Add a new entry
        studentAges.put("David", 23);
        System.out.println("After adding David: " + studentAges);
        // 4. Update a value for an existing key
        // If the key already exists, put() will update the value.
        studentAges.put("Alice", 22);
        System.out.println("After updating Alice's age: " + studentAges);
        // 5. Get a value by its key using get()
        Integer aliceAge = studentAges.get("Alice");
        System.out.println("Alice's age is: " + aliceAge); // Output: Alice's age is: 22
        // 6. Check if a key exists using containsKey()
        if (studentAges.containsKey("Bob")) {
            System.out.println("Bob is in the dictionary.");
        }
        // 7. Check if a value exists using containsValue()
        if (studentAges.containsValue(20)) {
            System.out.println("There is a student who is 20 years old.");
        }
        // 8. Remove an entry using remove()
        studentAges.remove("Charlie");
        System.out.println("After removing Charlie: " + studentAges);
        // 9. Get the size of the dictionary using size()
        System.out.println("Number of students: " + studentAges.size());
        // 10. Iterate over the dictionary
        System.out.println("\n--- Iterating over the dictionary ---");
        // Using a for-each loop with Map.entrySet()
        for (Map.Entry<String, Integer> entry : studentAges.entrySet()) {
            String name = entry.getKey();
            int age = entry.getValue();
            System.out.println("Name: " + name + ", Age: " + age);
        }
    }
}

Other Map Implementations

Java provides several other Map implementations, each with different characteristics. You should choose the one that best fits your needs.

Implementation Key Characteristics When to Use
HashMap Unordered, Fast (O(1)), Allows one null key. The default choice. Use when you need fast lookups and don't care about the order of elements.
LinkedHashMap Maintains insertion order. Slightly slower than HashMap. When you need to preserve the order in which elements were added.
TreeMap Sorted by keys (natural order or a custom Comparator). Slower (O(log n)). When you need the map to be sorted by its keys.
Hashtable Unordered, Thread-safe (synchronized), Does not allow null keys or values. Legacy class. Avoid in new code unless you need thread-safety without using ConcurrentHashMap. Use Collections.synchronizedMap(new HashMap<>()) or ConcurrentHashMap instead.

Example: LinkedHashMap vs. TreeMap

import java.util.*;
public class OtherMapsExample {
    public static void main(String[] args) {
        // LinkedHashMap: Maintains insertion order
        Map<String, String> linkedMap = new LinkedHashMap<>();
        linkedMap.put("Zebra", "Animal");
        linkedMap.put("Apple", "Fruit");
        linkedMap.put("Ball", "Object");
        System.out.println("LinkedHashMap (Insertion Order): " + linkedMap);
        // Output: LinkedHashMap (Insertion Order): {Zebra=Animal, Apple=Fruit, Ball=Object}
        // TreeMap: Sorted by natural order of keys (alphabetical for Strings)
        Map<String, String> treeMap = new TreeMap<>();
        treeMap.put("Zebra", "Animal");
        treeMap.put("Apple", "Fruit");
        treeMap.put("Ball", "Object");
        System.out.println("TreeMap (Sorted by Key): " + treeMap);
        // Output: TreeMap (Sorted by Key): {Apple=Fruit, Ball=Object, Zebra=Animal}
    }
}

Choosing the Right Map

  • Performance is key, order doesn't matter? -> HashMap
  • You need to remember the order you added items? -> LinkedHashMap
  • You need the keys to be sorted? -> TreeMap
  • You are in a multi-threaded environment? -> ConcurrentHashMap (modern, highly performant choice) or Collections.synchronizedMap().

Modern Java: Map.of() and Map.copyOf() (Java 9+)

For creating small, immutable maps, Java 9 introduced convenient factory methods.

  • Map.of(): Creates an immutable map with a fixed number of key-value pairs.
  • Map.copyOf(): Creates an immutable copy of an existing map.
import java.util.Map;
public class ImmutableMapsExample {
    public static void main(String[] args) {
        // Create an immutable map using Map.of()
        // Note: The syntax changes after 10 elements.
        Map<String, String> countryCapitals = Map.of(
            "USA", "Washington D.C.",
            "UK", "London",
            "France", "Paris"
        );
        System.out.println("Immutable Map: " + countryCapitals);
        // This will throw an UnsupportedOperationException because the map is immutable
        // countryCapitals.put("Germany", "Berlin");
        // Create an immutable copy of a mutable map
        Map<String, String> originalMap = new HashMap<>();
        originalMap.put("A", "1");
        originalMap.put("B", "2");
        Map<String, String> immutableCopy = Map.copyOf(originalMap);
        System.out.println("Immutable Copy: " + immutableCopy);
    }
}

Summary

Term Java Equivalent Description
Dictionary Map Interface The general concept for key-value storage.
Default Dictionary HashMap class The most common, fast, and unordered implementation.
Ordered Dictionary LinkedHashMap class A HashMap that remembers insertion order.
Sorted Dictionary TreeMap class A Map that keeps keys in sorted order.
Java中Dictionary类怎么用?-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇