一:Map
Map用于保存具有映射关系的数据,Map集合里保存着两组值,一组用于保存Map的ley,另一组保存着Map的value,也就是Map的 键值 和关键值 。具体举例 ,和查字典类似,通过key找到对应的value,通过页数找到对应的信息。用学生类来说,key相当于学号,value对应name,age,sex等信息。用这种对应关系方便查找。
二:基础了解
package cn.wyj.two;
/**
* Map是一个接口,我们平时多用它的实现类HashMap。
* 实现类 也是 继承 (继承结口)
*/
import java.util.HashMap;
import java.util.Map;
public class Demo3_map {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<Integer,String> m1 = new HashMap<Integer,String>();//这里需要用 HashMap 这是Map的实现类,
//Map是接口不能new
m1.put(1,"one");
m1.put(2, "two");
m1.put(3, "three");
System.out.println(m1.get(2));
System.out.println(m1.size());
System.out.println(m1.isEmpty());
System.out.println(m1.containsKey(1));//判断容器当中是否含有此键值的元素
System.out.println(m1.containsValue("four"));
Map<Integer,String> m2 = new HashMap<Integer,String>();
m2.put(4, "four");
m2.put(5, "five");
m2.putAll(m1);
System.out.println(m2);
}
}
三:进阶码(在一个类当中)
package cn.wyj.two;
import java.util.HashMap;
import java.util.Map;
public class Demo4_map2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
employee e1 = new employee(1005, "王永杰", 50000);
employee e2 = new employee(1002, "王二杰", 40000);
employee e3 = new employee(1003, "王三杰", 30000);
employee e4 = new employee(1001, "王四杰", 20000);
Map<Integer,employee> m1 = new HashMap<Integer,employee>();
m1.put(1005, e1);
m1.put(1002, e2);
m1.put(1003, e3);
m1.put(1001, e4);
employee emp = m1.get(1001);
System.out.println("姓名:"+emp.getName()+",薪水:"+emp.getSlary());
System.out.println(emp);//测试在Map容器当中不会有重复的元素,会直接将其覆盖掉
}
}
class employee{
private int id;
private String name;
private int slary;
public employee(int id, String name, int slary) {
super();
this.id = id;
this.name = name;
this.slary = slary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSlary() {
return slary;
}
public void setSlary(int slary) {
this.slary = slary;
}
public String toString(){
return "Id:" + this.id + " 姓名:" + this.name+" 薪水:" + this.slary;
}
}