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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.HashMap;
class ArrayTest {
public static void main(String[] args) {
// create an array
int[] a = {1,2,3};
int[] b = new int[]{1,2,3};
int[] c = new int[3];
for(int i=0; i<a.length; i++) {
c[i] = i+1;
}
// create an array list -> dynamic
ArrayList<Integer> arr = new ArrayList<>();
for(int i=0; i<3; i++){
arr.add(i+1);
}
// add element, O(1)
arr.add(99);
// appends all of the elements in the specified collection to the end of this list
arr.addAll(Collection c)
// access element, O(1)
int a1 = a[1];
int arr1 = arr.get(1);
// updata element, O(1)
a[1] = 11;
arr.set(index, value);
// remove element, O(n) as it needs to shuffle the elements to the "right" of removed point "left" by one
arr.remove(index);
// length of an array, O(1)
int aLen = a.length;
int arrSize = arr.size();
// contain an element?, O(n)
for(int i=0; i<a.length; i++) {
if(a[i]==value) {
System.out.println("Yes!");
}
}
boolean isValue = arr.contains(value);
// sort an array by built-in lib, O(nlogn)
// from small to big
Arrays.sort(a);
Collections.sort(arr);
// big to small
Arrays.sort(a, Collections.reverseOrder());
Collections.sort(arr, Collections.reverseOrder());
}
}
Class HashSetTest {
public static void main(String[] args) {
// create HashSet
HashSet<Integer> set = new HashSet<>();
// add element, O(1)
set.add(value);
// contains, O(1)
set.contains(value);
// delete element, O(1)
set.remove(value);
// size, O(1);
set.size();
}
}
Class HashMapTest {
public static void main(String[] args) {
// create HashTable
HashMap<Integer, String> map = new HashMap<>();
// add element, O(1)
map.put(key, value);
// update element, O(1)
map.put(key, value);
// get value, O(1)
map.get(key);
// get key sets
map.keySet();
// contains, O(1)
map.containsKey(key);
// values
map.values();
// length, O(1)
map.size();
// is empty, O(1)
map.isEmpty();
// provide value for new key which is absent
map.computeIfAbsent(key, k -> value);
}
}
|