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); } }
相关文章推荐
- HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别
- HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别
- HashMap和TreeMap区别详解以及底层实现
- HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别
- HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别
- HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别
- HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别
- (转)HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别
- HashMap,HashSet,Hashtable以及TreeMap的原理和区别
- HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别
- HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别(转)
- HashMap和ArrayMap实现原理的区别以及各自优势
- (11) java集合 ---- LinkedHashMap和HashMap等Map的比较使用以及 LinkedHashMap的实现原理
- HashMap底层实现原理---HashMap与HashTable区别
- hashmap底层实现原理以及常见的面试问题
- ArrayList、LinkedList和HashSet、TreeSet以及HashMap、TreeMap是如何实现存储的?
- java中hashmap的实现原理以及hashmap的正确使用
- iOS底层学习-KVC使用实践以及实现原理
- HashMap实现原理以及与其他Map实现类的区别
- hashMap,treeMap,LinkedHashMap使用以及区别分析