package com.net.xinfang.reflect; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; /*** * map-HashMap/HashTable/TreeMap * * @author xinfang * */ public class map006 { public void map() { Map<Integer, String> map = new HashMap<Integer, String>(); /*** * TreeMap的entrySet比keySet遍历效率高 */ Map<String,String> treemap=new TreeMap<String,String>(); Map<String,String> ht=new Hashtable<String,String>(); ht.put(String.valueOf(1),String.valueOf(1)); for(int i=0;i<2;i++){ treemap.put(String.valueOf(i),String.valueOf(i)); } Iterator<Entry<String,String>> tree=treemap.entrySet().iterator(); while(tree.hasNext()){ System.out.println(tree.next()); } map.put(0, "0");// 添加key-value map.put(1, "1"); //循环添加key-value for(int i=2;i<10;i++){ Integer key=i; String value=String.valueOf(i); map.put(key, value); } // keyset遍历-泛型-Iterator接口 Iterator<Integer> it = map.keySet().iterator(); while (it.hasNext()) { System.out.println(it.next()); } // entrykey遍历-泛型-Iterator接口 Iterator<Entry<Integer, String>> its = map.entrySet().iterator(); while (its.hasNext()) { System.out.println(its.next().getValue()); } // 第二种for-entry for (Map.Entry<Integer, String> entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } // 遍历map中的键 for (Integer key : map.keySet()) { System.out.println("Key = " + key); } // 遍历map中的值 for (String value : map.values()) { System.out.println("Value = " + value); } System.out.println(map.get(1));// 获取键值为1的值 System.out.println(map.size());// 获取map大小 System.out.println(map.equals(1));// 判断对象的内容是否相同 System.out.println(map.hashCode());// 获取hashcode System.out.println(map.isEmpty());// 空-true,非空-false System.out.println(map.remove(1));// 移除键值为1的值 System.out.println(map.values());// 获取值 System.out.println(map.getClass());// 获取类名 System.out.println(map.replace(0, "2"));// 替换键值为0的值为2 System.out.println(map.toString());// 转换为字符串 // map转换为List List<Integer> keyList = new ArrayList(map.keySet()); List<String> valueList = new ArrayList(map.values()); List<Entry> entryList = new ArrayList(map.entrySet()); // for遍历输出 for (Integer key : keyList) { System.out.println(key); } for (String value : valueList) { System.out.println(value); } for (Entry entry : entryList) { System.out.println(entry); } } public void searchList(String name) { LinkedList<String> list = new LinkedList<String>();// 链表对象 list.add("1");// 添加元素 list.add("2"); list.add("3"); list.push(name);// 入栈 list.pop();// 出栈 for (int i = 0; i < list.size(); i++) { if (name.equals(list.get(i))) { System.out.println("您要查询的信息存在!" + list.getFirst() + list.getLast()); } } if (list.contains(name)) { System.out.println("您要查询的信息存在!"); } } public static void main(String args[]) { map006 m6 = new map006(); m6.map(); m6.searchList("2"); } }