您的位置:首页 > 其它

TreeMap使用,底层原理和实现Comparable接口 ,HashMap和TreeMap的区别以及HashSet(也就是简化版的HashMap)

2019-08-11 16:15 519 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/weixin_44007988/article/details/99197484

TreeMap使用和底层原理和实现Comparable接口 ,HashMap和TreeMap的区别:HashMap线程不安全,效率高(允许key为null或者value为null),TreeMap线程安全,效率低(不允许key为null或者value为null)

package cn.com.collection;

import java.util.Map;
import java.util.TreeMap;

public class TestTreeMap {
public static void main(String[] args) {
Map<Integer,String> m = new TreeMap<>();
m.put(200,"o");
m.put(160,"d");
m.put(180,"z");
m.put(0,"a");
//        for (Integer a : m.keySet()) {
//            System.out.println(a+"---"+m.get(a));
//        }
//        System.out.println(m.get(180));
Map<Emp,String> m2 = new TreeMap<>();
m2.put(new Emp(1000,"小红",500),"小红是个好孩子");
m2.put(new Emp(500,"小白",250),"小白不是个好人");
m2.put(new Emp(650,"小玲",350),"小玲是个好姑娘");
m2.put(new Emp(300,"小军",350),"小军长得帅");
for (Emp key:m2.keySet()) {
System.out.println(key+"---"+m2.get(key));
}
}
}
class Emp implements Comparable<Emp>{
int id;
String name;
double salary;

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

@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;
}else {
return 0;
}
}
}

public Emp(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}

}

HashSet其实就是一个简化版的HashMap,key值不能重复

package cn.com.collection;

import java.util.HashSet;
import java.util.Set;

public class TestHashSet {
public static void main(String[] args) {
Set<Integer> s = new HashSet<>();
s.add(1);
s.add(2);
s.add(3);
s.add(3);
System.out.println(s);
//s.remove(3);
//System.out.println(s);
Set<Integer> s2 = new HashSet<>();
s2.add(3);
s2.add(5);
s2.add(6);
//s.addAll(s2);
System.out.println(s2);
//s是否是s2的子集
System.out.println(s.containsAll(s2));
//s.removeAll(s2);
//System.out.println(s);
//取交集
s.retainAll(s2);
System.out.println(s);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: