一般使用HashMap
import java.util.*;
/**
* 测试Map的使用方式
*/
public class MapTest {
public static void main(String[] args) {
Test02();
iterateListSet();
Test03();
}
//Map的常见用法
public static void Test01(){
Map m1 = new HashMap();//HashMap()替换
m1.put(1,"one");
m1.put(2,"two");
m1.put(3,"three");
System.out.println(m1);
m1.put(2,"二");//如果键重复,(equals()为核心进行判断),则会替换掉旧的键值对。
Object obj = m1.get(2);
System.out.println(obj);
System.out.println(m1);
System.out.println(m1.size());
System.out.println(m1.isEmpty());
System.out.println(m1.containsKey(4));//包含键3吗
System.out.println(m1.containsValue("three"));//包含值three吗
m1.remove(3);//从容器中移除键值对
System.out.println(m1);
Map m2 = new HashMap();
m2.put("yi","1111");
m2.put("er","2222");
m2.put(3,"3333");
m1.putAll(m2);
System.out.println(m1);
}
//泛型的简单应用
public static void Test02(){
List<String> list = new ArrayList();//泛型描述为String,存取、返回等操作就直接时String,不用强制转型。
list.add("aaa");
String str = list.get(0);
System.out.println(str);
Set<Integer> set = new HashSet();
set.add(1);
Map<String,String> map = new HashMap();
map.put("一","one");
map.put("二","two");
}
//遍历set、list
public static void iterateListSet(){
List<String> list = new ArrayList();
list.add("aaa");
list.add("bbb");
list.add("ccc");
//通过索引遍历list,只适合于List
for(int i=0;i<list.size();i++) {
String temp = list.get(i);
System.out.println(temp);
}
//通过增强for循环,可以用于Set
for(String temp:list) {
System.out.println(temp);
}
//使用Iterator对象,可以用于Set
for (Iterator<String> iter = list.iterator()/*初始化变量*/;iter.hasNext();/*判断有没有下一个*/) {
String temp = iter.next();//把当前正在遍历的对象返回,同时指向下一个。
System.out.println(temp);
}
}
//遍历Map(遍历key或者value)
public static void Test03(){
Map<String,String> map = new HashMap();
map.put("one","一");
map.put("two","二");
map.put("three","三");
//遍历键
Set<String> keys = map.keySet();
for(String temp:keys){
// System.out.println(temp);
System.out.println(temp+"----"+map.get(temp));
}
//遍历值
Collection<String> values = map.values();
for(String temp:values){
System.out.println(temp);
}
//使用EntrySet遍历key和value.
Set<Map.Entry<String,String>> entrySet = map.entrySet();
for(Map.Entry e:entrySet){
System.out.println(e.getKey()+"==="+e.getValue());
}
}
}