现实生活中,我们经常需要成对存储信息;
Map就是用来存储"键(key)-值(value)对"的。Map类中存储的"键值对"通过键来标识,所以"键对象"不能重复。
下面我们用代码来测试HashMap的使用:
首先定义一下HashMap
Map<Integer,String> m1=new HashMap<>();
其中键和值的类型可以是任意的;
下图为Map接口中常用的方法
使用put get方法:
m1.put(1, "one");
m1.put(2, "two");
m1.put(3, "three");
m1.put(4, "four");
System.out.println(m1.get(1));
输出结果为:one
size方法:
System.out.println(m1.size());
输出结果为:4
isEmpty()方法:
System.out.println(m1.isEmpty());
输出结果为:false
containsKey()方法与containsValue()方法:
System.out.println(m1.containsKey(3));
System.out.println(m1.containsValue("two"));
输出结果为:
true
true
putall()方法:
Map<Integer,String> m2=new HashMap<>();
m2.put(5, "伍");
m2.put(6, "陆");
m1.putAll(m2);
System.out.println(m1);
输出结果为:{1=one, 2=two, 3=three, 4=four, 5=伍, 6=陆}
Map中键不能重复,那么如果重复了会怎么样呢?
//map中键不能重复!
m1.put(3, "叁");
System.out.println(m1);
输出结果为:{1=one, 2=two, 3=叁, 4=four, 5=伍, 6=陆}
可见,如果重复,新的会把老的覆盖(是否重复是根据equals方法来判断的);
这节课的完整代码如下:
package cn.sxt.collection;
import java.util.HashMap;
import java.util.Map;
/**
* 测试HashMap的使用
* @author 韩文韬
*
*/
public class TestMap {
public static void main(String[] args) {
Map<Integer,String> m1=new HashMap<>();
m1.put(1, "one");
m1.put(2, "two");
m1.put(3, "three");
m1.put(4, "four");
// System.out.println(m1.get(1));
//
// System.out.println(m1.size());
//
// System.out.println(m1.isEmpty());
//
// System.out.println(m1.containsKey(3));
//
// System.out.println(m1.containsValue("two"));
Map<Integer,String> m2=new HashMap<>();
m2.put(5, "伍");
m2.put(6, "陆");
m1.putAll(m2);
System.out.println(m1);
//map中键不能重复!
m1.put(3, "叁");
System.out.println(m1);
}
}
下面是Map较为高级的用法!
package cn.sxt.collection;
import java.util.HashMap;
import java.util.Map;
/**
* 测试Map的常用方法
* @author 韩文韬
*
*/
public class TestMap2 {
public static void main(String[] args) {
Employee e1=new Employee(1001,"韩小狗",750);
Employee e2=new Employee(1002,"韩小猪",20000);
Employee e3=new Employee(1003,"韩小驴",50000);
Employee e4=new Employee(1001,"韩小屁",750);
Map<Integer,Employee> map=new HashMap<>();
map.put(1001, e1);
map.put(1002, e2);
map.put(1003, e3);
System.out.println(map);
map.put(1001,e4);
System.out.println(map);
System.out.println(map.get(1001).getEname());
}
}
//雇员信息
class Employee{
private int id;
private String ename;
private double salary;
public Employee(int id, String ename, double salary) {
super();
this.id = id;
this.ename = ename;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "id:"+id+" "+"姓名:"+ename+" "+"工资:"+salary;
}
}
输出结果为:
{1001=id:1001 姓名:韩小狗 工资:750.0, 1002=id:1002 姓名:韩小猪 工资:20000.0, 1003=id:1003 姓名:韩小驴 工资:50000.0}
{1001=id:1001 姓名:韩小屁 工资:750.0, 1002=id:1002 姓名:韩小猪 工资:20000.0, 1003=id:1003 姓名:韩小驴 工资:50000.0}
韩小屁
以后要经常温习这种基本的代码~