Java工作笔记-Map的基本用法

这段话是博客园一大神的,摘录下来:

(01) Map 是“键值对”映射的抽象接口。
(02) AbstractMap 实现了Map中的绝大部分函数接口。它减少了“Map的实现类”的重复编码。
(03) SortedMap 有序的“键值对”映射接口。
(04) NavigableMap 是继承于SortedMap的,支持导航函数的接口。
(05) HashMap, Hashtable, TreeMap, WeakHashMap这4个类是“键值对”映射的实现类。它们各有区别!

HashMap 是基于“拉链法”实现的散列表。一般用于单线程程序中。
Hashtable 也是基于“拉链法”实现的散列表。它一般用于多线程程序中。
WeakHashMap 也是基于“拉链法”实现的散列表,它一般也用于单线程程序中。相比HashMap,WeakHashMap中的键是“弱键”,当“弱键”被GC回收时,它对应的键值对也会被从WeakHashMap中删除;而HashMap中的键是强键。

TreeMap 是有序的散列表,它是通过红黑树实现的。它一般用于单线程中存储有序的映射。


下面这一坨是自己写的!

代码如下:

package my;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class main {

	public static void main(String[] args) {
		Map hashmap=new HashMap();
		hashmap.put("0", "Zero");
		hashmap.put("1", "One");
		hashmap.put("2", "Two");
		hashmap.put("3", "Three");
		hashmap.put("4", "Four");
		
		Set set=hashmap.entrySet();
		Iterator iterator=set.iterator();
		
		while(iterator.hasNext()) {
			Map.Entry mapentry=(Map.Entry)iterator.next();
			System.out.println(mapentry.getKey()+"/"+mapentry.getValue());
		}
		
		Map<Integer,String> hashmap2=new HashMap();
		hashmap2.put(0, "零");
		hashmap2.put(1, "一");
		hashmap2.put(2, "二");
		hashmap2.put(3, "三");
		hashmap2.put(4, "四");
		
		Set set2=hashmap2.entrySet();
		Iterator iterator2=set2.iterator();
		while(iterator2.hasNext()) {
			Map.Entry<Integer,String> mapentry=(Map.Entry<Integer,String>)iterator2.next();
			System.out.println(mapentry.getKey()+"/"+mapentry.getValue());
		}
	}

}

运行截图如下:



猜你喜欢

转载自blog.csdn.net/qq78442761/article/details/80279190