Java 类集映射类Map接口及其实现类详解

映射的接口是Map,在文档中如下定义:

.util

Interface Map

Type Parameters:
    K – the type of keys maintained by this map
    V – the type of mapped values

public interface Map

An object that maps keys to values. A map cannot contain duplicate keys; each key can map(映射) to at most one value.
This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface.
The Map interface provides three collection views(视图), which allow a map's contents to be viewed as a set(集合) of keys, collection(组合) of values, or set of key-value mappings(键值对). The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap  class, do not.   
// 成员接口:

static interface Map.Entry

A map entry (key-value pair).// 键值对
// 抽象方法集:

void clear()

Removes all of the mappings from this map (optional operation).

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> entrySet()

Returns a Set view of the mappings contained in this map.

boolean equals(Object o)

Compares the specified object with this map for equality.

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.

int hashCode()

Returns the hash code value for this map.

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 (optional operation).

void putAll(Map extends K,? extends V> m)

Copies all of the mappings from the specified map to this map (optional operation).

V remove(Object key)

Removes the mapping for a key from this map if it is present (optional operation).

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.
// 常用子类:
1.HashMap:

public class HashMap

extends AbstractMap

implements Map, Cloneable, Serializable;

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap  class is roughly(大致) equivalent(等价与) to Hashtable(哈希表类), except that it is unsynchronized(异步) and permits nulls(允许空).) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.          
// 构造:

HashMap()

Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).

HashMap(int initialCapacity)

Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75).

HashMap(int initialCapacity, float loadFactor)

Constructs an empty HashMap with the specified initial capacity and load factor.

HashMap(Map extends K,? extends V> m)

Constructs a new HashMap with the same mappings as the specified Map.

———–输出HashMap的所有key,value的Set、Collection视图

package com.mldn;

import .util.Map;

import .util.HashMap;

import .util.Set;

import java.util.Iterator;

import java.util.Collection;

public class MapDemo

{

public static void main(String[] args)

{

Map map = null; // 声明映射,键、值类型都为String

map = new HashMap(); // 用HashMap实例化

map.put(“k187”, “www.k187.com”); // 设置键值对

map.put(“China”, “中华人民共和国”);

map.put(“USA.”, “美利坚合众国”);

Set key = map.keySet(); // 返回当前map的所有key的Set视图

Iterator iter = key.iterator(); // 获取key集合的迭代器

while (iter.hasNext())

{

System.out.print(iter.next() + ” “); // 输出所有key

}

System.out.println(); // 换行

Collection value = map.values(); // 返回当前Map的所有value的Collection视图

Iterator viter = value.iterator(); // 获取迭代

while (viter.hasNext())

{

System.out.print(viter.next() + ” “); // 输出所有value

}

System.out.println(); // 换行

}

}

/*

administrator@xu-desktop:~$ java com.mldn.MapDemo

USA. k187 China

美利坚合众国 [url]www.k187.com[/url] 中华人民共和国

*/

——–TreeMap:排序
Map的子类:
可以对实现了Comparable接口的类声明的key进行排序!

public class TreeMap

extends AbstractMap

implements NavigableMap, Cloneable, Serializable;

—–实例:

package com.mldn;

import java.util.Map;

import java.util.TreeMap;

import java.util.Set;

import java.util.Iterator;

public class TreeMapDemo

{

public static void main(String[] args)

{

Map map = new TreeMap(); // 实例化映射

map.put(“A”, “www.k187.com”);

map.put(“B”, “www.baidu.com”);

map.put(“C”, “www.google.com”);

map.put(“D”, “www.sina.com”);

Set key = map.keySet(); // 获取所有的key

Iterator iter = key.iterator(); // 获取迭代器

while (iter.hasNext())

{

String str = iter.next(); // 读取当前key

System.out.println(str + “—->” + map.get(str)); // 获取当前key的映射

}

}

}

/*

ubuntu@xu-desktop:~$ java com.mldn.TreeMapDemo

A—->www.k187.com

B—->www.baidu.com

C—->www.google.com

D—->www.sina.com

// 发现TreeMap按升序排序key;主要用于排序;

*/

————-WeakHashMap:弱引用HashMap,

public class WeakHashMap

extends AbstractMap

implements Map

其中的实体在长不被使用时,将认为是垃圾,可以允许垃圾收集器回收该实体!
java中jdk1.2后定义四种对象引用级别:
1.强引用: 即使内存耗尽,jvm发生OutMemoryError才会终止程序;
2.软引用: 当内存不足时,进行回收以实现内存敏感的高速缓存;
3.弱引用: 无论内存是否不足,只要垃圾回收器执行了,就会将其收回;
4.虚引用: 和没引用一样;
WeakHashMap实现的是弱引用;
——WeakHashMap释放弱引用实体:

package com.mldn;

import java.util.Map;

import java.util.WeakHashMap;

public class WeakMapDemo

{

public static void main(String[] args)

{

Map map = new WeakHashMap(); // 实例化映射

map.put(new String(“A”), new String(“www.k187.com”)); // 匿名对象属于一种弱引用类型,将被gc回收

map.put(new String(“B”), new String(“www.baidu.com”));

map.put(“C”, “www.google.com”);

map.put(“D”, “www.sina.com”);

System.gc(); // 强制执行垃圾回收

System.out.println(map); // 输出当前的map对象

map.put(“E”, “www.k187.com”); // 再次放入键值对

System.out.println(map); // 再次查看当前map对象

}

}

/*

ubuntu@xu-desktop:~$ java com.mldn.WeakMapDemo

{C=www.google.com, D=www.sina.com}

{C=www.google.com, E=www.k187.com, D=www.sina.com}

// WeakHashMap可以在显式调用gc时释放其中的弱引用类型的实体!

// 但强引用的实体不会被释放!

*/

——————-输出Map对象:
一般Map不用与输出,而是查询;
–Map.Entry:键值对对象,实现Map的迭代输出
package com.mldn;
import java.util.Map;
import java.util.Hashtable;
import java.util.Set;
import java.util.Iterator;
public class MapDemo
{
        public static void main(String[] args)
        {
                Map map = null;        // 声明映射,键、值类型都为String
                map = new Hashtable();        // 用HashMap实例化
                map.put(“k187”, “www.k187.com”);        // 设置键值对
                map.put(“China”, “中华人民共和国”);
                map.put(“USA.”, “美利坚合众国”);
                Set> entry = map.entrySet();        // 1.返回当前Map的键值对实体对象 的Set视图
                Iterator> iter = entry.iterator();        // 2.获取Set对象的迭代
                while (iter.hasNext())
                {
                        Map.Entry mapEntry = iter.next();        // 3.读取当前键值对对象
                        System.out.println(mapEntry.getKey() + ” ” + mapEntry.getValue()); // 4.获取键值对对象的键、值属性
                }       
        }
}
/*
administrator@xu-desktop:~$ java com.mldn.MapDemo
China 中华人民共和国
k187 www.k187.com
USA. 美利坚合众国
*/

声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 智乐兔
转载请注明:转自《Java 类集映射类Map接口及其实现类详解
本文地址:https://www.zhiletu.com/archives-120.html
关注公众号:智乐兔

赞赏

wechat pay微信赞赏alipay pay支付宝赞赏

上一篇
下一篇

相关文章

在线留言

你必须 登录后 才能留言!

在线客服
在线客服 X

售前: 点击这里给我发消息
售后: 点击这里给我发消息

智乐兔官微