一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - JAVA HashSet和TreeSet 保證存入元素不會重復的操作

JAVA HashSet和TreeSet 保證存入元素不會重復的操作

2020-09-29 00:42貓球球 Java教程

這篇文章主要介紹了JAVA HashSet和TreeSet 保證存入元素不會重復的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

Set是一種數據集合。它與List同樣繼承與Collection接口。

它與Collection接口中的方法基本一致,并沒有對Collection接口進行功能進行功能上的擴充,只是比Collection接口更嚴格了。與List不同的是,Set中的元素是無無需的,并且都以某種規則保證存入的元素不會出現重復

它的特點也就是:

1. 元素不會出現重復。

2. 元素是無序的。(存取無序)

3. 元素可以為空。

每種類型的Set所使用的避免元素重復的規則都是不同的,今天我們主要還是看HashSetTreeSet

第一種是HashSet:

HashSet

我們先來看看HashSet的構造器是怎么樣的:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
static final long serialVersionUID = -5024744406713321676L;
 
  private transient HashMap<E,Object> map;
 
  // Dummy value to associate with an Object in the backing Map
  private static final Object PRESENT = new Object();
 
  /**
   * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
   * default initial capacity (16) and load factor (0.75).
   */
  public HashSet() {
    map = new HashMap<>();
  }

令人驚訝的是HashSet的結構里實際上就包含了一個HashMap,而初始化HashSet就是給這個對象的Map賦值一個空HashMap對象。

再讓我們來看一看插入操作:

?
1
2
3
public boolean add(E e) {
   return map.put(e, PRESENT)==null;
 }

add操作實際上是向map中插入了一條記錄,是以我們所要存的元素為key,以一個空對象為value的記錄。

到了這不實際上我們已經能明白,set里的元素是不可能重復的,因為我們對hashMap同一個key進行put,并不會生成新的記錄,而是對上一條記錄進行覆蓋而已。但是hashMap是如何判斷Key是否是同一個的呢?讓我們來看以下代碼

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class SetTest {
 
 public class Obj {
 public String name;
 public Obj(String name) {
  this.name=name;
 }
 }
 
 public static void main(String[] args) {
 Set<String> strSet = new HashSet<String>();
 String str1 = new String("123");
 String str2 = new String("123");
 strSet.add(str1);
 strSet.add(str2);
 System.out.println(str1 == str2);
 for(String str : strSet) {
  System.out.println(str);
 }
 Set<Obj> objSet = new HashSet<Obj>();
 Obj o1 = new SetTest().new Obj("1");
 Obj o2 = new SetTest().new Obj("1");
 objSet.add(o1);
 objSet.add(o2);
 for(Obj str : objSet) {
  System.out.println(str.name);
 }
 }
}

結果為:

?
1
2
3
4
false
123
1
1

那讓我們繼續看看,在put方法中java代碼又干了什么呢?(汗,感覺我從Set講到HashMap去了)

?
1
2
3
public V put(K key, V value) {
   return putVal(hash(key), key, value, false, true);
 }

在下一層的代碼里,先對key本身進行了一個轉化hash(key),這個方法的源碼是:

?
1
2
3
4
static final int hash(Object key) {
   int h;
   return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
 }

判斷key是否為空,如果為空就返回0,不然就對key值取hashCode并與h>>>16的值做異或操作,異或是一種位運算,在此就不做解釋了。而>>>是一種位移操作, 在這個hash()方法里,實際上是生成了這個key值對應的hash值。這里做了什么計算,我準備放到另一篇博客里進行討論,無論怎么樣,我們都知道對hashmap put相同的key值,不會重復的,這個是由HashMap的機制由hashCode也就是Hash碼解決的,關于HashMap的結構和具體方法,我會在另外一篇博客中單獨列出。

 

TreeSet

當我們new 一個TreeSet的時候,實際上是創建了一個TreeMap,并將這個TreeMap賦值給了TreeSet對象的m.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
   * The backing map.
   */
  private transient NavigableMap<E,Object> m;
 
  // Dummy value to associate with an Object in the backing Map
  private static final Object PRESENT = new Object();
 
  /**
   * Constructs a set backed by the specified navigable map.
   */
  TreeSet(NavigableMap<E,Object> m) {
    this.m = m;
  }
/**
   * Constructs a new, empty tree set, sorted according to the
   * natural ordering of its elements. All elements inserted into
   * the set must implement the {@link Comparable} interface.
   * Furthermore, all such elements must be <i>mutually
   * comparable</i>: {@code e1.compareTo(e2)} must not throw a
   * {@code ClassCastException} for any elements {@code e1} and
   * {@code e2} in the set. If the user attempts to add an element
   * to the set that violates this constraint (for example, the user
   * attempts to add a string element to a set whose elements are
   * integers), the {@code add} call will throw a
   * {@code ClassCastException}.
   */
  public TreeSet() {
    this(new TreeMap<E,Object>()); // 將一個新生成的TreeMap空對象賦值給m,也就是上一方法
  }

而用這個構造器定義的TreeMap是沒有指定對比器的:

?
1
2
3
public TreeMap() {
   comparator = null;
 }

讓我們來看一下TreeSet的add方法的全過程:

?
1
2
3
public boolean add(E e) {
    return m.put(e, PRESENT)==null; // 如果返回值為空則表示我們插入了一個新的元素,如果返回值為非空,則表明我們插入的元素已經存在。
  }

實際上也就是向TreeMap以你的要放入的元素為key, 空對象為value做一次put。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public V put(K key, V value) {
   Entry<K,V> t = root; // 定義t為根節點
   if (t == null) { // 如果根節點為空
     compare(key, key); // type (and possibly null) check // 對自身做對比,如果有對比器就用對比器的規則進行對比,如果沒有,就用元素自身對比的規則進行對比。為0則相等。我覺得這波其實沒有意義,就是一個空的對比。
 
     root = new Entry<>(key, value, null); // 新建一個空的根節點
     size = 1; // 設置大小為1
     modCount++; //對0做+1
     return null; // 返回空值,表示插入成功。
   }
   int cmp;
   Entry<K,V> parent;
   // split comparator and comparable paths
   Comparator<? super K> cpr = comparator; // 用本treeMap的對比器對cpr賦值
   if (cpr != null) { // 如果定義的對比器不為空(在TreeSet里是為空的,我們之間說到過)
     do {
       parent = t;
       cmp = cpr.compare(key, t.key);
       if (cmp < 0)
         t = t.left;
       else if (cmp > 0)
         t = t.right;
       else
         return t.setValue(value);
     } while (t != null);
   }
   else { // 如果對比器為空(在這種情況下是為空的)
     if (key == null) // 如果key為空就拋出錯誤
       throw new NullPointerException();
     @SuppressWarnings("unchecked")
     Comparable<? super K> k = (Comparable<? super K>) key;// 生成可比較的對象Comparable
     do {
       parent = t; 將父節點(最初是根節點)賦值給parent
       cmp = k.compareTo(t.key); //對我們要插入的key與根節點的keyj進行對比
       if (cmp < 0) // 對比后值小于0,則表示我們插入的key小于根節點的key,就讓父節點往左走,并循環直至命中
         t = t.left;
       else if (cmp > 0) // 對比后值大于0,則表示我們插入的key小于根節點的key,就讓父節點往右走,并循環直至命中
         t = t.right;
       else //當命中,用我們的值替換原有的值一次保證不插入重復的key,并返回替換后的對象
         return t.setValue(value);
     } while (t != null);
   }
   Entry<K,V> e = new Entry<>(key, value, parent); // 如果沒有在樹中命中,則新生成一個樹節點此時parent的父節點已經遍歷到了某個葉子節點。
   if (cmp < 0) // 如果你的這個值是小于葉子節點的,則插入左邊,大于則插入右邊
     parent.left = e;
   else
     parent.right = e;
   fixAfterInsertion(e); // 對整棵樹做平衡修正
   size++; // size值加1表示我們插入了一個值
   modCount++; // modCount也加1
   return null;
 }

整個過程就是:

1. 先查看根節點是否存在,如果不存在就直接吧這個節點放在根節點上。

2. 如果根節點存在就依順序向下查找,如果找到對應的節點,就把該節點的值替換。

3. 如果遍歷到了葉子節點仍然沒有命中,那么就向葉子節點插入一個子節點,小就在左邊大就在右邊。

因為TreeSet插入的值都是空對象,只有key是有效的,key又是相等就覆蓋,所以不會重復

以上這篇JAVA HashSet和TreeSet 保證存入元素不會重復的操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。

原文鏈接:https://blog.csdn.net/sinat_38232376/article/details/83655755

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 513热点网深夜影院影院诶 | 日本红怡院亚洲红怡院最新 | 午夜爽喷水无码成人18禁三级 | 视频免费在线 | 日本一区二区三区国产 | 日韩毛片免费线上观看 | 秋霞午夜| 免费被靠视频动漫 | 王者荣耀瑶白色液体 | 亚洲天堂视频在线免费观看 | 亚洲无人区乱码中文字幕 | 91李宗精品72集在线观看 | 潘金莲西门庆一级淫片aaaaaa | 亚洲天堂成人在线观看 | 久久久乱码精品亚洲日韩 | 免费看一级大片 | 成人中文字幕在线观看 | 太紧太深了受不了黑人 | 玩乳h文奶水和尚 | 亚洲AV久久久久久久无码 | 亚洲六月丁香婷婷综合 | 欧美特级午夜一区二区三区 | 欧美肥胖老妇做爰变态 | 亚洲精品午夜级久久久久 | 天美传媒tm0087| 四虎永久免费地址 | 18xxxx中国| 人人澡 人人澡碰人人看软件 | 亚洲99久久无色码中文字幕 | 成年人福利视频 | 视频一区二区国产 | 亚洲精品老司机福利在线播放 | 天天白天天谢天天啦 | 99视频在线免费观看 | 五月婷婷伊人网 | 亚洲日本中文字幕天天更新 | 精品人伦一区二区三区潘金莲 | 波多野结中文字幕在线69视频 | 美女被到爽流动漫 | 99精品热线在线观看免费视频 | 四神集团1涨奶是第几章 |