码迷,mamicode.com
首页 > 其他好文 > 详细

TreeMap和Comparable接口

时间:2019-10-08 20:27:34      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:线程安全   nbsp   com   turn   return   stat   his   str1   for   

备注: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<Integer, String> str1 = new TreeMap<Integer, String>();

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<emp, String> str2 = new TreeMap<emp, String>();
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<emp>{
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<o.salary){
return -1;
}else if (this.id>o.id) {
return 1;
}else if(this.id<o.id){
return-1;
}else {
return 0 ;
}
}


}

TreeMap和Comparable接口

标签:线程安全   nbsp   com   turn   return   stat   his   str1   for   

原文地址:https://www.cnblogs.com/LuJunlong/p/11637705.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!