Hashset、Treeset 和 LinkedHashset、Hashmap 之间的主要区别是什么?它在 Java 中是如何工作的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20217414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 00:22:42  来源:igfitidea点击:

What is the main difference between Hashset, Treeset and LinkedHashset, Hashmap and how does it work in Java?

javacollectionshashsetlinkedhashset

提问by Achiever

I just understand that LinkedHashSet does not allows duplicate elements when it is inserting. But, I dont understand how does Hashset works in Hava? I know a bit that Hashtable is used in Hashset so the hashtable used to store the elements and here also does not allow the duplicate elements. Then, Treeset is also similar to Hashset it also does not allows duplicate entries so unique elements will be seen and it follows ascending order.

我只知道 LinkedHashSet 在插入时不允许重复元素。但是,我不明白 Hashset 在 Hava 中是如何工作的?我知道在 Hashset 中使用了 Hashtable,因此用于存储元素的哈希表在这里也不允许重复元素。然后,Treeset 也与 Hashset 类似,它也不允许重复条目,因此将看到唯一元素并且它遵循升序。

I have one more doubt regarding HashMap - Hashmap does not maintains order. It may have one null key and multiple null values. I just dont understand this and what does it mean actually? Any practical example for this?

我对 HashMap 还有一个疑问——Hashmap 不维护秩序。它可能有一个空键和多个空值。我只是不明白这一点,这实际上意味着什么?这有什么实际例子吗?

I know a bit, Hashmap used to work based on this - Key and values used to put in buckets also bucket has unique numbers. So that, can identify and get the key and value from the buckets. When I put the key/value pair in the bucket of which identifier is the hash code of the key.

我知道一点,Hashmap 曾经基于此工作 - 用于放入存储桶的键和值也存储桶具有唯一的数字。这样,就可以从桶中识别并获取键和值。当我将键/值对放入其标识符是键的哈希码的桶中时。

For an eg: Hash code of the key is 101 so it is stored in bucket 101. One bucket can store more than key and value pairs. Suppose take an example as Object1 is "A", object2 is "A"and object3 is "B" then it has a same Hash code. So, it stores the different objects by sharing the same Hashcode in same bucket. My doubt is, objects with same Hashcode should be equal and different objects should have different Hashcodes?

例如:键的哈希码是 101,所以它存储在桶 101 中。一个桶可以存储多个键和值对。假设举个例子,对象1是“A”,对象2是“A”,对象3是“B”,那么它有相同的哈希码。因此,它通过在同一个桶中共享相同的 Hashcode 来存储不同的对象。我的疑问是,具有相同 Hashcode 的对象应该相等,不同的对象应该具有不同的 Hashcodes?

This is the program using HashSet:

这是使用 HashSet 的程序:

    import java.util.*;
    public class Simple{
    public static void main(String[] args){
    HashSet hh=new HashSet();
    hh.add("D");
    hh.add("A");
    hh.add("B");
    hh.add("C");
    hh.add("a");        
    System.out.println("Checking the size is:"+hh.size()+"");
    System.out.println(hh);

    Iterator i=hh.iterator();
    while(i.hasNext()){
    System.out.println(i.next());
    }      
    }
    }

Output is,

输出是,

Checking the size is:5
[D, A, B, a, C]
D
A
B
a
C

My doubt is, why "a" is inserting in between "B" and "C".

我的疑问是,为什么在“B”和“C”之间插入“a”。

Now, I am using LinkedHashSet so,

现在,我使用 LinkedHashSet 所以,

public class Simple{
public static void main(String[] args){
    LinkedHashSet hh=new LinkedHashSet();
            hh.add("D");
            hh.add("A");
    hh.add("B");
    hh.add("C");
            hh.add("a");  

        System.out.println("Checking the size is:"+hh.size()+"");
    System.out.println(hh);

    Iterator i=hh.iterator();
    while(i.hasNext()){
        System.out.println(i.next());
    }      
}
}

I just understand that, it follows insertion order and it avoids duplicate elements. So the output is,

我只是明白,它遵循插入顺序并避免重复元素。所以输出是,

Checking the size is:5
[D, A, B, C, a]
D
A
B
C
a

Now, Using Treeset:

现在,使用树集:

import java.util.*;
public class Simple{
public static void main(String[] args){
    TreeSet hh=new TreeSet();
            hh.add("1");
            hh.add("5");
            hh.add("3");
            hh.add("5");
            hh.add("2");
            hh.add("7");  

System.out.println("Checking the size is:"+hh.size()+"");
System.out.println(hh);

    Iterator i=hh.iterator();
    while(i.hasNext()){
        System.out.println(i.next());
    }      
}
}

Here, I just understand that - Treeset follows ascending order.

在这里,我只明白 - Treeset 遵循升序。

The output is,
Checking the size is:5
[1, 2, 3, 5, 7]
1
2
3
5
7

Then my doubt is, how does Hashset works in Java? And I know that LinkedHashset follows doubly linkedlist. If it uses doubly linked list then how does it stores the elements? What does mean by doubly linkedlist and how does it works? Then where all these three Hashset, Treeset, LinkedHashset would be used in Java and which one has better performance in Java?

那么我的疑问是,Hashset 在 Java 中是如何工作的?而且我知道 LinkedHashset 遵循双链表。如果它使用双向链表,那么它如何存储元素?双链表是什么意思,它是如何工作的?那么Hashset、Treeset、LinkedHashset这三个在Java中会用到哪里,哪一个在Java中性能更好呢?

采纳答案by Stephen C

My doubt is, why "a" is inserting in between "B" and "C".

我的疑问是,为什么在“B”和“C”之间插入“a”。

A TreeSet orders the entries.

TreeSet 对条目进行排序。

A LinkedHashSet preserves the insertion order.

LinkedHashSet 保留插入顺序。

A HashSet does not preserve the order of insertion, and is does not sort/order the entries. That means that when you iterate over the set, the entries are returned in an order that is hard to fathom ... and of no practical significance. There is no particular "reason" that "a"is inserted at that point. That's just how it turned out ... given the set of input keys and the order in which they were inserted.

HashSet 不保留插入顺序,也不对条目进行排序/排序。这意味着当您迭代集合时,条目以难以理解的顺序返回......并且没有实际意义。在这一点上没有"a"插入特定的“原因” 。结果就是这样……考虑到输入键集和它们插入的顺序。

My only doubt is, how does Hashset works in Java.

我唯一的疑问是,Hashset 在 Java 中是如何工作的。

It is implemented a hash table. Read the Wikipedia page on hash tablesfor a general overview, and the source code of java.util.HashMapand java.util.HashSetfor the details.

它实现了一个哈希表。阅读关于维基百科页面哈希表的总体概述,以及源代码java.util.HashMapjava.util.HashSet详细。

The short answer is that HashSetand HashMapare both a hash table implemented as an array of hash chains.

简短的回答是,HashSetHashMap都是作为散列链数组实现的散列表。

And I know that, LinkedHashset follows doubly linkedlist. If it uses doubly linked list then how does it stores the elements?

我知道,LinkedHashset 遵循双链表。如果它使用双向链表,那么它如何存储元素?

LinkedHashSetis essentially a hash table with an additional linked list that records the insertion order. The elements are stored in the main hash table ... and that is what provides fast lookup. Again, refer to the source code for details.

LinkedHashSet本质上是一个带有记录插入顺序的附加链表的哈希表。元素存储在主哈希表中......这就是提供快速查找的原因。同样,请参阅源代码了解详细信息。

What does mean by doubly linkedlist and how does it works?

双链表是什么意思,它是如何工作的?

Read the article in Wikipedia on doubly linked lists.

阅读维基百科中关于双向链表的文章。



Then where all these three Hashset, Treeset, Linkedhashset would be used in Java and which one has better performance in java?

那么Hashset、Treeset、Linkedhashset这三个在Java中会用到哪里,哪一个在java中性能更好呢?

There are a number of things to think about when choosing between these three classes (and others):

在这三个类(和其他类)之间进行选择时,需要考虑很多事情:

  • Do they provide the required functionality. For example, we've already seen that they have differentbehaviour with respect to the order of iteration.

  • Do they have the required concurrency properties? For example, are they thread-safe? do they deal with contention? do they allow concurrent modification?

  • How much space do they require?

  • What are the performance (time) characteristics.

  • 它们是否提供了所需的功能。例如,我们已经看到它们在迭代顺序方面有不同的行为。

  • 它们是否具有所需的并发属性?例如,它们是线程安全的吗?他们处理争用吗?他们允许并发修改吗?

  • 他们需要多少空间?

  • 什么是性能(时间)特性。

On the last two points?

关于最后两点?

  • A TreeSetuses the least space, and a LinkedHashSetuses the most.

  • A HashSettends to be fastest for lookup, insertion and deletion for larger sets, and a TreeSettends to be slowest.

  • ATreeSet使用的空间最少,而A使用的空间LinkedHashSet最多。

  • HashSet对于较大的集合,A在查找、插入和删除方面往往最快,而 aTreeSet往往最慢。

回答by Pierre Arlaud

I'll be succinct.

我会简明扼要。

A Set follows the math theory of sets. A Set (AbstractSet is the supertype in Java) is similar to a list except it cannot have the same element twice.

集合遵循集合的数学理论。Set(AbstractSet 是 Java 中的超类型)类似于列表,但它不能有两次相同的元素。

HashSet implements it with a HashMap, TreeSet implements it with a Tree, LinkedHashset implements it with a doubly-linked list.

HashSet用HashMap实现,TreeSet用Tree实现,LinkedHashset用双向链表实现。

回答by Andrei Nicusan

First of all, you need to know that all Setimplementations share the same feature: they don't allow duplicates. It's not just a feature of the LinkedHashSet.

首先,您需要知道所有Set实现都具有相同的功能:它们不允许重复。这不仅仅是LinkedHashSet.

Second, one important difference is that, out of the 3 set types you asked about, the TreeSetis a sorted set, that is elements are ordered according to their natural ordering or according to a logic described imperatively using a Comparatoror implementing the Comparableinterface.

其次,一个重要的区别是,在您询问的 3 种集合类型中,TreeSet是有序集合,即元素根据其自然顺序或根据使用 aComparator或实现Comparable接口命令式描述的逻辑进行排序。

Switching to the difference between HashSetand LinkedHashSet, please note that LinkedHashSetis a subclass of HashSet. They are not sorted sets.

切换到之间的差异HashSet,并LinkedHashSet请注意,这LinkedHashSet是一个子类HashSet。它们不是排序集。

HashSetis the fastest implementation of a set and it ensures the uniqueness of elements using (first) their hash value returned by the hashCode()method and (then) their equals()method. Behind the scenes, it uses a HashMap.

HashSet是集合的最快实现,它使用(首先)hashCode()方法返回的散列值和(然后)它们的equals()方法来确保元素的唯一性。在幕后,它使用HashMap.

The LinkedHashSetensures consistent ordering over the elements of the set with the help of a LinkedList, which basic HashSets do not provide.

LinkedHashSeta 的帮助下确保对集合元素的一致排序LinkedList,basic HashSets 不提供。

回答by Reetika

  • HashSet does't preserve the order of elements.So you can't identify its order.
  • LinkedHashSet preserve the order as elements are added in set. It keep the order as we insert in it.

  • TreeSet maintains the order of element. TreeSet is slowest because it arrange its elements after every element addition or deletion.

    Otherwise it all repends on your requirement , whether you need ordered list, thread-safe etc.

  • HashSet 不保留元素的顺序。因此您无法识别其顺序。
  • LinkedHashSet 保留元素添加到集合中时的顺序。它保持我们插入时的顺序。

  • TreeSet 维护元素的顺序。TreeSet 最慢,因为它在每次添加或删除元素后排列其元素。

    否则,这一切都取决于您的要求,无论您是否需要有序列表、线程安全等。

回答by Dhina k

HashMap accepts key-value pair,It allows null value for both key and Value and HashMap is Unsynchronized. HasTable accepts key-value pair,It didn't allows null value for both key and Value and HasTable is Synchronized.

HashMap 接受键值对,它允许键和值都为空值,HashMap 是非同步的。HasTable 接受键值对,它不允许键和值都为空值,并且 HasTable 是同步的。

for more info

了解更多信息