map接口、hashmap常用方法

 

 

注意:map中键不能重复(是否重复是根据equals方法判断),否则新的会覆盖为旧的

 

范例:

public class TestMap {
public static void main(String[] args) {
Map<Integer, String> m1 = new HashMap<Integer, String>();

m1.put(1, "aaa");
m1.put(2, "bbb");
m1.put(3, "ccc");

System.out.println(m1.get(1));
System.out.println(m1);

System.out.println(m1.size());
System.out.println(m1.isEmpty());
System.out.println(m1.containsKey(2));
System.out.println(m1.containsValue("ccc"));

Map<Integer, String> m2 = new HashMap<Integer, String>();
m2.put(4, "si");
m2.put(5, "wu");

m1.putAll(m2);

System.out.println(m1);

//map中键不能重复,否则新的会覆盖为旧的
m1.put(3, "san");
System.out.println(m1);
}
}

 

 

 

map存放对象方法示例:(在value值中存放对象即可)

public class TestMap02 {
public static void main(String[] args) {

Employee e1 = new Employee(1001, "aaa",200000);
Employee e2 = new Employee(1002, "bbb",160000);
Employee e3 = new Employee(1003, "ccc",100000);
Employee e4 = new Employee(1004, "ddd",200000);

Map<Integer, Employee> map = new HashMap<Integer, Employee>();

map.put(1001, e1);
map.put(1002, e2);
map.put(1003, e3);
map.put(1004, e4);

Employee emp = map.get(1001);
System.out.println(emp.getSname());

System.out.println(map);
}

}

posted @ 2019-09-25 23:59  Princess1  阅读(312)  评论(0编辑  收藏  举报