From online resources

Set

HashSet is much faster than TreeSet (constant-time versus log-time for most operations like add, remove and contains) but offers no ordering guarantees like TreeSet.

HashSet

  • class offers constant time performance for the basic operations (add, remove, contains and size).
  • it does not guarantee that the order of elements will remain constant over time
  • iteration performance depends on the initial capacity and the load factor of the HashSet.
    • It's quite safe to accept default load factor but you may want to specify an initial capacity that's about twice the size to which you expect the set to grow.

TreeSet

  • guarantees log(n) time cost for the basic operations (add, remove and contains)
  • guarantees that elements of set will be sorted (ascending, natural, or the one specified by you via its constructor) (implements SortedSet)
  • doesn't offer any tuning parameters for iteration performance
  • offers a few handy methods to deal with the ordered set like first()last()headSet(), and tailSet() etc

Important points:

  • Both guarantee duplicate-free collection of elements
  • It is generally faster to add elements to the HashSet and then convert the collection to a TreeSet for a duplicate-free sorted traversal.
  • None of these implementation are synchronized. That is if multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally.
  • LinkedHashSet is in some sense intermediate between HashSet and TreeSet. Implemented as a hash table with a linked list running through it, however it provides insertion-ordered iteration which is not same as sorted traversal guaranteed by TreeSet.

So choice of usage depends entirely on your needs but I feel that even if you need an ordered collection then you should still prefer HashSet to create the Set and then convert it into TreeSet.

  • e.g. SortedSet<String> s = new TreeSet<String>(hashSet);

Map is an important data structure.

1. Map Overview

There are 4 commonly used  implementations of Map in Java SE - HashMap, TreeMap, Hashtable and LinkedHashMap. If we use one sentence to describe each implementation, it would be the following:

  • HashMap is implemented as a hash table, and there is no ordering on keys or values.
  • TreeMap is implemented based on red-black tree structure, and it is ordered by the key.
  • LinkedHashMap preserves the insertion order
  • Hashtable is synchronized, in contrast to HashMap.

This gives us the reason that HashMap should be used if it is thread-safe, since Hashtable has overhead for synchronization.

2. HashMap

If key of the HashMap is self-defined objects, then equals() and hashCode() contract need to be followed.

class Dog {
String color;
 
Dog(String c) {
color = c;
}
public String toString(){
return color + " dog";
}
}
 
public class TestHashMap {
public static void main(String[] args) {
HashMap hashMap = new HashMap();
Dog d1 = new Dog("red");
Dog d2 = new Dog("black");
Dog d3 = new Dog("white");
Dog d4 = new Dog("white");
 
hashMap.put(d1, 10);
hashMap.put(d2, 15);
hashMap.put(d3, 5);
hashMap.put(d4, 20);
 
//print size
System.out.println(hashMap.size());
 
//loop HashMap
for (Entry entry : hashMap.entrySet()) {
System.out.println(entry.getKey().toString() + " - " + entry.getValue());
}
}
}

Output:

white dog – 5
black dog – 15
red dog – 10
white dog – 20

Note here, we add "white dogs" twice by mistake, but the HashMap takes it. This does not make sense, because now we are confused how many white dogs are really there.  The Dog class should be defined as follows:

class Dog {
String color;
 
Dog(String c) {
color = c;
}
 
public boolean equals(Object o) {
return ((Dog) o).color == this.color;
}
 
public int hashCode() {
return color.length();
}
 
public String toString(){
return color + " dog";
}
}

Now the output is:

red dog – 10
white dog – 20
black dog – 15

The reason is that HashMap doesn't allow two identical elements. By default, the hashCode() and equals() methods implemented in Object class are used. The default hashCode() method gives distinct integers for distinct objects, and the equals() method only returns true when  two references refer to the same object. Check out the hashCode() and equals() contract if this is not obvious to you.

3. TreeMap

A TreeMap is sorted by keys. Let's first take a look at the following example to understand the "sorted by keys" idea.

class Dog {
String color;
 
Dog(String c) {
color = c;
}
public boolean equals(Object o) {
return ((Dog) o).color == this.color;
}
 
public int hashCode() {
return color.length();
}
public String toString(){
return color + " dog";
}
}
 
 
public class TestTreeMap {
public static void main(String[] args) {
Dog d1 = new Dog("red");
Dog d2 = new Dog("black");
Dog d3 = new Dog("white");
Dog d4 = new Dog("white");
 
TreeMap treeMap = new TreeMap();
treeMap.put(d1, 10);
treeMap.put(d2, 15);
treeMap.put(d3, 5);
treeMap.put(d4, 20);
 
for (Entry entry : treeMap.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}
}

Output:

Exception in thread “main” java.lang.ClassCastException: collection.Dog cannot be cast to java.lang.Comparable
at java.util.TreeMap.put(Unknown Source)
at collection.TestHashMap.main(TestHashMap.java:35)

Since TreeMaps are sorted by keys, the object for key has
to be able to compare with each other, that's why it has to implement
Comparable interface. For example,  you use String as key, because
String implements Comparable interface.  Let's change the Dog, and make
it comparable.

class Dog implements Comparable{
String color;
int size;
 
Dog(String c, int s) {
color = c;
size = s;
}
 
public String toString(){
return color + " dog";
}
 
@Override
public int compareTo(Dog o) {
return  o.size - this.size;
}
}
 
public class TestTreeMap {
public static void main(String[] args) {
Dog d1 = new Dog("red", 30);
Dog d2 = new Dog("black", 20);
Dog d3 = new Dog("white", 10);
Dog d4 = new Dog("white", 10);
 
TreeMap treeMap = new TreeMap();
treeMap.put(d1, 10);
treeMap.put(d2, 15);
treeMap.put(d3, 5);
treeMap.put(d4, 20);
 
for (Entry entry : treeMap.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}
}

Output:

red dog – 10
black dog – 15
white dog – 20

It is sorted by key, i.e., dog size in this case.  If "Dog d4 = new Dog("white", 10);" is replaced with "Dog d4 = new Dog("white", 40);", the output would be:

white dog – 20
red dog – 10
black dog – 15
white dog – 5

The reason is that TreeMap now uses compareTo() method to compare keys. Different sizes make different dogs!

4. Hashtable

From Java Doc:  The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.

5. LinkedHashMap

LinkedHashMap is a subclass of HashMap. That means it inherits the features of HashMap. In addition, the linked list preserves the insertion-order.  Let's replace the HashMap with LinkedHashMap using the same code used for HashMap.

class Dog {
String color;
 
Dog(String c) {
color = c;
}
 
public boolean equals(Object o) {
return ((Dog) o).color == this.color;
}
 
public int hashCode() {
return color.length();
}
 
public String toString(){
return color + " dog";
}
}
 
public class TestHashMap {
public static void main(String[] args) {
 
Dog d1 = new Dog("red");
Dog d2 = new Dog("black");
Dog d3 = new Dog("white");
Dog d4 = new Dog("white");
 
LinkedHashMap linkedHashMap = new LinkedHashMap();
linkedHashMap.put(d1, 10);
linkedHashMap.put(d2, 15);
linkedHashMap.put(d3, 5);
linkedHashMap.put(d4, 20);
 
for (Entry entry : linkedHashMap.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}
}

Output is:

red dog – 10
black dog – 15
white dog – 20

The difference is that if we use HashMap the output could be the following - the insertion order is not preserved.

red dog – 10
white dog – 20
black dog – 15

TreeSet VS HashSet VS LinkedHashSet; TreeMap VS HashMap VS LinkedHashMap的更多相关文章

  1. TreeMap,HashMap,LinkedHashMap区别,很简单解释

    TreeMap,HashMap,LinkedHashMap之间的区别和TreeSet,HashSet,LinkedHashSet之间的区别相似. TreeMap:内部排序. HashMap:无序. L ...

  2. Java集合系列(三):HashSet、LinkedHashSet、TreeSet的使用方法及区别

    本篇博客主要讲解Set接口的三个实现类HashSet.LinkedHashSet.TreeSet的使用方法以及三者之间的区别. 注意:本文中代码使用的JDK版本为1.8.0_191 1. HashSe ...

  3. HashSet、LinkedHashSet、TreeSet

    以下内容基于jdk1.7.0_79源码: 关于HashSet.LinkedHashSet.TreeSet Set接口的实现类,最大特点是不允许出现重复元素: HashSet:基于HashMap实现,一 ...

  4. Java Set 常用集合 HashSet、LinkedHashSet、TreeSet

    Java 中的 Set 是非常常用的数据类型.Set 是无序的 Collection,Java Set 有三个常用的实现类,分别是:HashSet.LinkedHashSet.TreeSet 本文基于 ...

  5. 规则集之探究何时使用HashSet、LinkedHashSet以及TreeSet?

    前言 Java集合框架三种主要类型的集合:规则集(Set).线性表(List).队列(Queue).Set用来存储不可重复的元素:List用来存储有元素构成的有序的集合:而Queue则用于存储用先进先 ...

  6. Java集合框架(二)—— HashSet、LinkedHashSet、TreeSet和EnumSet

    Set接口 前面已经简绍过Set集合,它类似于一个罐子,一旦把对象'丢进'Set集合,集合里多个对象之间没有明显的顺序.Set集合与Collection基本上完全一样,它没有提供任何额外的方法. Se ...

  7. 一、集合框架(关于ArrayList,LinkedList,HashSet,LinkedHashSet,TreeSet)

    一.ArrayList 解决了数组的局限性,最常见的容器类,ArrayList容器的容量capacity会随着对象的增加,自动增长.不会出现数组边界的问题. package collection;   ...

  8. 09 Collection,Iterator,List,listIterator,Vector,ArrayList,LinkedList,泛型,增强for,可变参数,HashSet,LinkedHashSet,TreeSet

    09 Collection,Iterator,List,listIterator,Vector,ArrayList,LinkedList,泛型,增强for,可变参数,HashSet,LinkedHas ...

  9. HashSet、LinkedHashSet和TreeSet

    关键技术: HashSet采用散列函数对元素进行排序,是专门为快速查询而设计的.存入HashSet的对象必须定义hashCode方法. TreeSet采用红黑树的数据结构进行排序元素,使用它可以从Se ...

随机推荐

  1. autoit脚本-从基本的函数用法开始

    适配浏览器:目前了解的有ie浏览器 MsgBox 显示可选提示超时的消息框 _ArrayDisplay _arraydisplay($aArray)  ;$aArra一般为数组,方法用于展示表格展示数 ...

  2. ready

    // 定义一个动物类 function Animal (name) { // 属性 this.name = name || 'Animal'; // 实例方法 this.sleep = functio ...

  3. Qt信号槽第5个参数

    1.Qt::AutoConnection: 默认值,使用这个值则连接类型会在信号发送时决定.如果接收者和发送者在同一个线程,则自动使用Qt::DirectConnection类型.如果接收者和发送者不 ...

  4. 实验9-1 编写一个存储过程proc_test_func

    在TestDB数据库中,编写一个存储过程proc_test_func,要求如下: 1)输入参数 一个整型的输入参数 @value 2)要求在一个select语句返回: @value的绝对值, 此绝对值 ...

  5. springboot2.0 JPA配置自定义repository,并作为基类BaseRepository使用

    springboot2.0 JPA配置自定义repository,并作为基类BaseRepository使用 原文链接:https://www.cnblogs.com/blog5277/p/10661 ...

  6. 钉钉授权第三方WEB网站扫码登录

    一.阅读开发文档 首先阅读钉钉官方的开发文档,扫码登录其实用的是官方文档描述的第二种方式,即将钉钉登录二维码内嵌到自己页面中,用户使用钉钉扫码登录第三方网站,网站可以拿到钉钉的用户信息. 二.准备工作 ...

  7. JS 基本类型和引用类型---JS 学习笔记(一)

    本文参考了focusxxxxy的博客,感谢他的知识分享. 一 基本类型和引用类型的值 ECMAScript 变量包含两种不同数据类型的值:基本类型和引用类型. 也有其他的叫法,比如原始类型和对象类型, ...

  8. HDU 6495 冰水挑战

    Problem Description Polar Bear Pitching helps you crystallize your message. The stage could not be a ...

  9. Jmeter转换成中文模式

    本片文章转至:https://blog.csdn.net/him2014/article/details/79603887 下载安装好Jmeter后默认的是英文,对于我这种学渣来说简直就是受到了100 ...

  10. MySQL中Decimal类型和Float Double的区别 & BigDecimal与Double使用场景

    MySQL中存在float,double等非标准数据类型,也有decimal这种标准数据类型. 其区别在于,float,double等非标准类型,在DB中保存的是近似值,而Decimal则以字符串的形 ...