创建:Map<String,Integer> map =new HashMap<String, Integer>();
其中键值对中的值不可为int,必须为Integer,前者是代表key(关键标识符,类似sql中的主键),后者代表 value,代表主键对应的值
加入值:map.put("A",1);
map.put("B",2) ;通过put的方式加入,对应出事创建好的参数类型
移除值:map.remove("A") 通过主键辨别移除相应的值
通过key判断这个值是不是已经存贮,返回一个boolean类型:map.containsKey("A");
通过value判断这个值是不是已经存贮:map.containsValue(2);
map的大小:map.size();
通过主键得到主键对应的value值:map.get("A");
通过遍历map中的key输出:for(String key:map.keySet()) .你起初定义的是什么类型,就什么类型的变量
System.out.println(key);
通过遍历map中的value输出:for(Integer value:map.values())
System.out.println(value);
import java.util.*;
public class Main
{
public static void main(String args[])
{
Map<String,Integer> map =new HashMap<String, Integer>();
map.put("A", 1);
map.put("B", 2);
System.out.println(map.containsKey("A"));
System.out.println(map.containsValue(3));
for(String key:map.keySet())
System.out.println(key);
for(Integer value:map.values())
System.out.println(value);
System.out.println(map.get("A"));
map.remove("A");
System.out.println(map.size());
map.put("B", 2);
}
}
输出:
true
false
A
B
1
2
1
1
提醒:
import java.util.*;
public class Main
{
public static void main(String args[])
{
Map<String,Integer> map=new HashMap<String,Integer>();
map.put("A", 1);
map.put("A", 1);
System.out.println(map.size()); //输出 1
}
}
import java.util.*;
public class Main
{
public static void main(String args[])
{
Map<String,Integer> map=new HashMap<String,Integer>();
map.put("A", 1);
map.put("B", 1);
System.out.println(map.size()); //输出 2
}
}
可以尝试做做这个例题,掌握map
练习:http://blog.csdn.net/yiyuan_chen/article/details/69488094