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
|
// Create an array
int[] a = {1,2,3};
int[] b = new int[]{1,2,3};
int[] c = new int[3]; // The initilization is [0,0,0]
for (int i=0, i < c.length; i++){
c[i] = i + 1;
}
ArrayList<Integer> d = new ArrayList<>(); // Integer is an object
for (int i = 0; i < 3; i++){
d.add(i+1)
}
// Add an element
// An addiotnal empty array should be declared for a, b, c.
// For ArrayList, the length of the array could be ignored in declaration.
d.add(100); // [1,2,3,100] - O(1)
d.add(3, 99); // [1,2,3,99,100] - O(N), i.e. 100 should be moved backwards for 99.
// Access an element - O(1)
int item1 = a[1];
int item2 = d.get(1);
// Update an element - O(1)
a[1] = 0; // [1,0,3,100]
d.set(1, 0); // [1,0,3,99,100], where the 1st arg is the index; the 2nd arg is the new value.
// Remove an element for ArrayList - O(N)
d.remove(99) // [1,2,3,100]
// Get the length of array - O(1), i.e. there is a cnt var inside
int aLen = a.length; // String.length(), Array.length
int dLen = d.size();
// Traverse an array - O(N)
for (int i = 0; i < a.length; i++) { ... }
for (int i = 0; i < d.size(); i++) { ... }
// Find an element - O(N)
// Loop should be adopted for a, b, c;
// For ArrayList, use .contains()
boolean is100 = d.contains(100)
// Sort an array - O(N*log(N))
Array.sort(a) // Read from the last to reverse the array
Collections.sort(d)
Collections.sort(d, Collections.reverseOrder())
|