TreeMap和Comparable接口

备注:HashMap线程不安全,效率高,允许key、value为空

HasTable线程安全、效率低、不允许key或value为空

 

TreeMap在存储时会自动调用comparable方法进行排序,当key为类时可自行调用comparable接口

 

范例:

package cn.study.lu.four;

import java.util.TreeMap;


public class TestTreeMap {
public static void main(String[] args) {
TreeMap str1 = new TreeMap();

str1.put(1001, "aaa");
str1.put(333, "bbb");
str1.put(181, "ccc");
str1.put(9991, "ddd");
for (int k:str1.keySet()) {
System.out.println(k +"---"+str1.get(k));
}
System.out.println(str1);

TreeMap str2 = new TreeMap();
str2.put(new emp(1001, "张三", 10000),"aaa");
str2.put(new emp(1002, "王五", 60000),"bbb");
str2.put(new emp(1003, "里斯", 20000),"ccc");
str2.put(new emp(1004, "赵六", 20000),"ddd");
for(emp i:str2.keySet()) {
System.out.println(i+"---"+str2.get(i));
}
}
}


class emp implements Comparable{
int id;
String name;
int salary;
public emp(int id, String name, int salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}


public String toString() {
return ("id:"+id+",name:"+name+",salary:"+salary);
}

public int compareTo(emp o) {
if (this.salary>o.salary) {
return 1;
}else if(this.salary
return -1;
}else if (this.id>o.id) {
return 1;
}else if(this.id
return-1;
}else {
return 0 ;
}
}


}

你可能感兴趣的:(TreeMap和Comparable接口)