TreeMap的使用
摘要
本文主要讲解TreeMap的特性和使用
TreeMap的特性
TreeMap类实现了Map接口,也是一种哈希表,最大的特性莫过于有序,其keySet()返回的key的顺序是有序的,为从小到大。
TreeMap的使用
public class TestTreeMap {
public static void main(String[] args) {
Map<Integer, String> treemap1 = new TreeMap<>();
treemap1.put(20,"aa");
treemap1.put(3,"bb");
treemap1.put(6,"cc");
//打印的顺序是有序的
for(Integer key : treemap1.keySet()){
System.out.println(key + "---" + treemap1.get(key));
}
Map<Emp, String> treemap2 = new TreeMap<>();
treemap2.put(new Emp(100,"张三",50000),"张三是一个好小伙");
treemap2.put(new Emp(200,"李四",5000), "李四工作不积极");
treemap2.put(new Emp(150,"王五",6000),"王五工作还不错");
treemap2.put(new Emp(50,"刘六",6000),"刘六工作不行");
for(Emp key : treemap2.keySet()){
System.out.println(key + "---" + treemap2.get(key));
}
}
}
//Emp类实现了Comparable接口,所以Emp就是可以比较的
class Emp implements Comparable<Emp>{
int id;
String name;
double salary;
public Emp(int id, String name, double salary){
this.id = id;
this.name = name;
this.salary = salary;
}
//Emp的对象哪个大,哪个小,由这个函数说了算,如果返回值小于0,说明当前对象是小的,返回值大于0,说明当前对象是大的,否则这两个对象是相等的
@Override
public int compareTo(Emp o) {
if(this.salary > o.salary) return 1;
else if(this.salary < o.salary) return -1;
else{
if(this.id > o.id) return 1;
else if(this.id < o.id) return -1;
return 0;
}
}
@Override
public String toString() {
return "id:" + id + "," + "name:" + name + "," + "salary:" + salary;
}
}