MapTest java 核心编程

时间:2020-10-29 09:22:51   收藏:0   阅读:21

简介

类似c++map

code

/*
 * @Author: your name
 * @Date: 2020-10-27 21:15:06
 * @LastEditTime: 2020-10-27 21:19:36
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /java/Employee.java
 */

public class Employee implements Comparable<Employee> {
	private String name;
	private double salary;
	
	public Employee(String name, double salary) {
		this.name = name;
		this.salary = salary;
	}
    
    public Employee(String name) {
		this.name = name;
		this.salary = -1;
	}
    public String toString(){
        return "[name=" + name +  "]";
    }
	public String getName(){
		return name;
	}

	public double getSalary() {
		return salary;
	}
	
	public void raiseSalary(double byPercent) {
		double raise = salary * byPercent / 100;
		salary += raise;
	}
	
	@Override
	public int compareTo(Employee other) {
		// TODO Auto-generated method stub
		return Double.compare(salary,  other.salary);
	}
}

/*
 * @Author: your name
 * @Date: 2020-10-27 21:08:20
 * @LastEditTime: 2020-10-27 21:18:24
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /java/MapTest.java
 */
import java.util.*;

public class MapTest {
    public static void main(String[] args) {
        Map<String, Employee> staff = new HashMap<>();
        staff.put("144-25-5464", new Employee("Amy Lee"));
        staff.put("567-24-2546", new Employee("Harry Hacker"));
        staff.put("157-62-7935", new Employee("Gary Cooper"));
        staff.put("456-62-5527", new Employee("Frrancesca Curz"));
        
        System.out.println(staff);
        staff.remove("567-24-2546");
        staff.put("456-62-5527", new Employee("Francesca Miller"));
        System.out.println(staff.get("157-62-7935"));
        staff.forEach((k, v)->System.out.println("key=" + k + ", value=" + v));
    }
}

result

{157-62-7935=[name=Gary Cooper], 144-25-5464=[name=Amy Lee], 456-62-5527=[name=Frrancesca Curz], 567-24-2546=[name=Harry Hacker]}
[name=Gary Cooper]
key=157-62-7935, value=[name=Gary Cooper]
key=144-25-5464, value=[name=Amy Lee]
key=456-62-5527, value=[name=Francesca Miller]

发现确实完成了元素的删除和替换

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!