java.util.Map接口

来源:互联网 发布:光学字符识别软件 编辑:程序博客网 时间:2024/06/08 09:04
先看代码
public class A {public void linkedhashmap() {System.out.println("LinkedHashMap");Map<Integer, Integer> linkedHashmap = new LinkedHashMap();linkedHashmap.put(6, 6);linkedHashmap.put(100, 100);linkedHashmap.put(3, 3);linkedHashmap.put(5, 5);Iterator<Map.Entry<Integer, Integer>> it = linkedHashmap.entrySet().iterator();while (it.hasNext()) {Map.Entry<Integer, Integer> entry = it.next();System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());}}public void hashmap() {System.out.println("HashMap");Map<Integer, Integer> hashmap = new HashMap();hashmap.put(6, 6);hashmap.put(100, 100);hashmap.put(3, 3);hashmap.put(5, 5);Iterator<Map.Entry<Integer, Integer>> it = hashmap.entrySet().iterator();while (it.hasNext()) {Map.Entry<Integer, Integer> entry = it.next();System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());}}public void treemap() {System.out.println("TreeMap");Map<Integer, Integer> treemap = new TreeMap();treemap.put(6, 6);treemap.put(100, 100);treemap.put(3, 3);treemap.put(5, 5);Iterator<Map.Entry<Integer, Integer>> it = treemap.entrySet().iterator();while (it.hasNext()) {Map.Entry<Integer, Integer> entry = it.next();System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());}}public static void main(String[] args) {A a = new A();a.linkedhashmap();a.hashmap();a.treemap();}}


HashMap不保证顺序,TreeMap根据key值顺序,LinkedHashMap根据插入的顺序。


输入结果为:


LinkedHashMap
key= 6 and value= 6
key= 100 and value= 100
key= 3 and value= 3
key= 5 and value= 5
HashMap
key= 3 and value= 3
key= 100 and value= 100
key= 5 and value= 5
key= 6 and value= 6
TreeMap
key= 3 and value= 3
key= 5 and value= 5
key= 6 and value= 6
key= 100 and value= 100


HashMap:



TreeMap:



LinkedHashMap:




hash


0 0
原创粉丝点击