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 collisionO(n) - use
hash index - save data:
O(1), if hash collisionO(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 indexwill 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
- ๐ create another
new arrayinside array - save both
[9, 99]inhash index 9 - to search
hash index 9, go toindex 9, and searchnew array
โ Hash Code Function
- function that can change
valueinto certain lengthhash code - same
valueshould always return samehash 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()andequals() hashCode(): to createhash indexequals(): to get, search data withequals()- ๐๐ป a good
hash functionis 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()andequals()to use hash index - Rehashing: ๐ฅ if a lot of hash collision occurs, create bigger(*2)
new arrayโก๏ธ copy oldarray
โ๏ธ LinkedHashSet
HashSetโLinkedList(order)- value โ
node - use
nodeto connect, know front and afternodeof myself - get all linkedHashSet: in input order(linked with
node)
โ๏ธ TreeSet
- binary tree
- can have order(input
3, 1, 2โก๏ธ ordered in1, 2, 3) add, search data:
O(logN)parent nodeโchild node- binary tree: can have two
child node - binary search tree:
left child nodeis smaller thanright 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.
