今天用到了键-值对,于是想起了 Java 的 Map,由于之前并不很熟悉,就看了下源码,如下:

/*
 * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package java.util;
public interface Map<K,V> {
    // Query Operations
    int size();
    boolean isEmpty();
    boolean containsKey(Object key);
    boolean containsValue(Object value);
    V get(Object key);

    // Modification Operations
    V put(K key, V value);
    V remove(Object key);

    // Bulk Operations
    void putAll(Map<? extends K, ? extends V> m);
    void clear();

    // Views
    Set<K> keySet();
    Collection<V> values();
    Set<Map.Entry<K, V>> entrySet();
    interface Entry<K,V> {
        K getKey();
        V getValue();
        V setValue(V value);
        boolean equals(Object o);
        int hashCode();
    }

    // Comparison and hashing
    boolean equals(Object o);
    int hashCode();
}

PS: 看过后才清楚的知道 Map 是一个接口,而 HashMap 则是实现 Map 接口的一个类。而且觉得源码写得很美!以后要多看。

version: jdk1.7.0_79

 

Map 的遍历,示例代码:

Iterator entries = ReadFile.map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = (Map.Entry) entries.next();
    String key = (String) entry.getKey();
    String value = (String) entry.getValue();
    System.out.print("key: " + key + ", " + "value: " + value + "\n");
}

参考:java中map,set的简单使用