-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayMain2.java
More file actions
47 lines (41 loc) · 1.52 KB
/
Copy pathArrayMain2.java
File metadata and controls
47 lines (41 loc) · 1.52 KB
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
package collection.array;
import java.util.Arrays;
public class ArrayMain2 {
public static void main(String[] args) {
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
System.out.println(Arrays.toString(arr));
//배열의 첫번째 위치에 추가
//기본 배열의 데이터를 한 칸씩 뒤로 밀고 배열의 첫번쨰 위치에 추가
System.out.println("배열의 첫번째 위치에 3 추가 O(n)");
int newValue = 3;
addFirst(arr, newValue);
System.out.println(Arrays.toString(arr));
//index 위치에 추가
//기본 배열의 데이터를 한 칸씩 뒤로 밀고 배열의 index 위치에 추가
System.out.println("배열의 index(2) 위치에 4 추가 O(n)");
int index = 2;
int value = 4;
addAtIndex(arr, index, value);
System.out.println(Arrays.toString(arr));
System.out.println("배열의 마지막 위치에 5 추가 O(1)");
addLast(arr, 5);
System.out.println(Arrays.toString(arr));
}
public static void addLast(int[] arr, int newValue) {
arr[arr.length-1] = newValue;
}
public static void addAtIndex(int[] arr, int index, int newValue){
for(int i = arr.length-1; i> index; i-- ){
arr[i] = arr[i-1];
}
arr[index] = newValue;
}
public static void addFirst(int[] arr, int newValue){
for(int i = arr.length-1; i>0; i--){
arr[i] = arr[i-1];
}
arr[0] = newValue;
}
}