-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyArrayList.java
More file actions
113 lines (100 loc) · 3.12 KB
/
Copy pathMyArrayList.java
File metadata and controls
113 lines (100 loc) · 3.12 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
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
112
113
package ArrayList;
public class MyArrayList{
private Object[] data;
private int size;
private int index; //다음 데이터 추가 위치 index
public MyArrayList(){
this.size = 1;
this.data = new Object[this.size];
this.index = 0;
}
//데이터 추가 함수
public void add(Object obj){
if(this.index == this.size){//할당한 배열이 다 찬 경우
doubling();
}
data[this.index] = obj;
this.index++;
}
// 배열 크기를 늘리는 함수
private void doubling(){
this.size = this.size*2;
Object[] newData = new Object[this.size]; //배열의 크기를 2배로 늘려줌
for(int i=0; i<this.index; i++){
newData[i] = data[i]; //기존 배열 복사
}
this.data = newData;
}
// index로 data 가져오는 경우
public Object get(int i) throws Exception{
if(i> this.index-1){// 가지고 있는 데이터보다 큰 경우
throw new Exception("ArrayIndexOutOfBound");
}
else if(i<0){
throw new Exception("NegativeValue");
}
return this.data[i];
}
//데이터 제거
public void remove(int i) throws Exception{
if(i > this.index-1){ // 가지고 있는 데이터보다 큰 경우
throw new Exception("ArrayIndexOutOfBound");
}
else if(i<0){
throw new Exception("NegativeValue");
}
//삭제할 데이터 위치 기준으로 한칸씩 앞으로 덮어씌움
for(int x=i; x < this.index; x++){
data[x] = data[x+1];
}
this.index--;
}
//데이터 삽입
public void insert(int i, Object obj) throws Exception{
if(i > this.index){ // 가지고 있는 데이터보다 큰 경우
throw new Exception("ArrayIndexOutOfBound");
}
else if(i<0){
throw new Exception("NegativeValue");
}
if(this.index == this.size){//할당한 배열이 다 찬 경우
doubling();
}
// 데이터를 추가할 자리까지 데이터를 역순으로 뒤로 이동
if(i<this.index){
for(int x = this.index-1; x >= i; x--){
this.data[x+1] = this.data[x];
}
}
this.data[i] = obj;
this.index++;
}
//데이터 검색
public boolean contains(Object obj){
for(int i = 0; i<this.index; i++){
if(data[i].equals(obj))
return true;
}
return false;
}
// ArrayList에 저장된 데이터 크기 측정
public int size(){
return this.index;
}
// ArrayList가 비어있는지 확인
public boolean isEmpty(){
return this.index == 0;
}
//데이터 출력
@Override
public String toString(){
StringBuilder sb = new StringBuilder("[");
for(int i = 0; i < this.index; i++){
sb.append(data[i]);
if(i < this.index - 1)
sb.append(", ");
}
sb.append("]");
return sb.toString();
}
}