Post

Set, Hash, HashSet, LinkedHashSet, TreeSet

List ๐Ÿ†š Set

  • List: duplicationโญ•๏ธ, indexโญ•๏ธ, used for order
  • Set: duplicationโŒ, no index โŒ, used for search

โœ… Set

  • uniqueness, no duplication
  • no order, no index
  • fast search

โœ… Hash

  • ๐Ÿ‘๐Ÿป search, get value: O(1), if hash collision O(n)
  • use hash index
  • save data: O(1), if hash collision O(n)
  • use division
  • use remainder as hash index
1
2
3
4
5
6
Integer[] intArray = new Integer[10]; //array size: 10

//14 -> 14%10 -> hash index: 4
intArray[4] = 14;
//99 -> 99%10 -> hash index: 9
intArray[9] = 99;
  • hash index will always be smaller than array size

๐Ÿ’ฅ Hash collision

  • ๐Ÿ’ฅ division remainder(hash index) can be same
  • if hash collision occurs, hash index will be the same
1
2
3
9 % 10 -> hash index 9
99 % 10 -> hash index 9
// what should we have in array index 9? both [9, 99] in new array

Image

  • ๐Ÿ’Š create another new array inside array
  • save both [9, 99] in hash index 9
  • to search hash index 9, go to index 9, and search new array

โœ… Hash Code Function

  • function that can change value into certain length hash code
  • same value should always return same hash code
1
2
3
4
//hashCode function that change string into int
hashCode("A") = 65
hashCode("B") = 66
hashCode("AB") = 131
  • by using hash code function, we can save any type of data on hashSet
1
2
3
4
5
MyHashSetV2 set = new MyHashSetV2(10);
Member memberA = new Member("idA");
set.add(memberA); //save Member on hashSet

idA.hashCode(); //can get hashCode of memberA
  • need to override hashCode() and equals()
  • hashCode(): to create hash index
  • equals(): to get, search data with equals()
  • ๐Ÿ‘๐Ÿป a good hash function is widely distributed, ๐Ÿ’ฅ less hash collision

โ˜‘๏ธ HashSet

  • no duplication
  • no order
  • add data: O(1)
  • search data: O(1)
  • get all hashSet: in random order(save with hash index)
  • must override hashCode() and equals() to use hash index
  • Rehashing: ๐Ÿ’ฅ if a lot of hash collision occurs, create bigger(*2) new array โžก๏ธ copy old array

โ˜‘๏ธ LinkedHashSet

  • HashSet โž• LinkedList(order)
  • value โž• node
  • use node to connect, know front and after node of myself
  • get all linkedHashSet: in input order(linked with node)

โ˜‘๏ธ TreeSet

  • binary tree
  • can have order(input 3, 1, 2 โžก๏ธ ordered in 1, 2, 3)
  • add, search data: O(logN)

  • parent node โž• child node
  • binary tree: can have two child node
  • binary search tree: left child node is smaller than right child node
  • when add data, order and save the data
  • search: if value is smaller than node โžก๏ธ go left, if bigger โžก๏ธ go right, O(logN)
    • ๊ฒ€์ƒ‰ํ•  ๋•Œ ํ•œ๋ฒˆ์— ์ ˆ๋ฐ˜์„ ๋‚ ๋ ค๋ฒ„๋ฆด ์ˆ˜ ์žˆ๋‹ค
  • get all tree: in ascending order(smallโžก๏ธbig), ์ค‘์œ„์ˆœํšŒ(left node โžก๏ธ myself โžก๏ธ right node)

โœ…

โœ…

โœ…

โœ…

โœ…

โœ…

This post is licensed under CC BY 4.0 by the author.