一、简介
- Map就是用来存储“键(key)-值(value)”对的.
- 通过键寻找value,所以键不能重复.
- 数组的本质也是一种键值对,区别就是索引一般是数字,而Map的Key可以是任意对象(字符串,数字),相当于把数组的索引范围扩的更大,使用更方便.
- 实际开发中较为常用.
二、Map的常用方法实例
- (1)存储数据(V put(K key, V value))
Map<Integer,String> map = new HashMap<>(16);
map.put(1,"a");
map.put(2,"b");
map.put(3,"c");
map.put(4,"d");
map.put(5,"e");
map.put(6,"f");
map.put(7,"g");
map.put(8,"h");
map.put(9,"i");
- (2)取出数据(V get(Object key))
String s = map.get(1);
System.out.println(s);
- (3)添加对象操作
import java.util.HashMap;
import java.util.Map;
/**
* @author liuyangos8888
*/
public class MapHasObject {
public static void main(String[] args) {
Employee e1 = new Employee(1001, "张三", 50000);
Employee e2 = new Employee(1002, "李四", 5000);
Employee e3 = new Employee(1003, "龙五", 6000);
Employee e4 = new Employee(1001, "五六", 7000);
Map<Integer, Employee> map = new HashMap<>();
map.put(1001, e1);
map.put(1002, e2);
map.put(1003, e3);
map.put(1001, e4);
Employee emp = map.get(1001);
System.out.println(emp.getEmployeeName());
System.out.println(map);
}
}
/**
* 新建职员对象
*/
class Employee {
/**
* 工号
*/
private int id;
/**
* 姓名
*/
private String employeeName;
/**
* 薪资
*/
private double salary;
public Employee(int id, String employeeName, double salary) {
this.id = id;
this.employeeName = employeeName;
this.salary = salary;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", employeeName='" + employeeName + '\'' +
", salary=" + salary +
'}';
}
}
结果:
标签:map,java,自定义,id,public,Employee,源码,put,employeeName From: https://www.cnblogs.com/liuyangfirst/p/13882126.html