MyArrayList.java
public class MyArrayList {
int initCapacity = 10;
int[] elementData;
int size; // # of data added
int currentCapacity;
int result;
public MyArrayList() {
elementData = new int[initCapacity];
size=0;
currentCapacity = initCapacity;
}
public int get(int index) {
return elementData[index];
}
public void add(int data) {
if(size == currentCapacity) {
// array size 확대 <== 2배 크기의 array 를 만들어서 기존 data copy한 뒤 새 data를 추가
int [] newArray = new int [currentCapacity*2];
for(int i=0; i<size; i++) {
newArray[i]= elementData[i];
}
elementData = newArray;
currentCapacity = currentCapacity*2;
}else {
elementData[size] = data;
size++;
}
}
public void add(int index , int data) {
if(size != currentCapacity) {
int [] newArray = new int [currentCapacity*2];
for(int i=size; i>=index; i--) {
newArray[i+1]= elementData[i];
}
for(int k=0; k<=index; k++){
newArray[k] = elementData[k];
}
++size;
++currentCapacity;
elementData = newArray;
elementData[index] = data;
}
}
public int remove(int index) {
int data = elementData[index];
this.removeValue(index, data);
return elementData[index];
}
public void removeValue(int index, int data) {
if(size != currentCapacity){
int [] newArray = new int [currentCapacity*2];
for(int i=size; i>index; i--){
newArray[i-1] = elementData[i];
}
for(int k=0; k<index; k++){
newArray[k] = elementData[k];
}
--size;
--currentCapacity;
elementData = newArray;
}
}
public int sizeOf() {
return size;
}
public int arrSize() {
return currentCapacity;
}
public String toString() {
String ret = "";
for(int i=0; i<size; i++)
ret = ret + elementData[i] + ", ";
return ret;
}
}
MyArrayListMain.java
import java.util.ArrayList;
import java.util.Random;
public class MyArrayListMain {
public static void main(String[] args) {
Random random = new Random() ;
int index = 3;
int value = 77;
MyArrayList me = new MyArrayList();
for(int i=0; i<20; i++) {
me.add((int) random.nextInt(99));
}
System.out.println(me.toString() + "---- [arraySize: " + me.arrSize() + "]");
System.out.println(index + "번 인덱스 값: " + me.get(index));
me.add(index, value);
System.out.println();
System.out.println(index + "번 인덱스에 " +value+ "을 추가합니다.");
System.out.println();
System.out.println(me.toString() + "---- [arraySize: " + me.arrSize() + "]");
System.out.println(index + "번 인덱스 값: " + me.get(index));
System.out.println();
System.out.println(index+ "번 인덱스 값을 삭제합니다. ") ;
me.remove(index);
System.out.println();
System.out.println(me.toString() + "---- [arraySize: " + me.arrSize() + "]");
System.out.println(index + "번 인덱스 값: " + me.get(index));
}
}
'🗣️ Programming Language > Java' 카테고리의 다른 글
[Java] 자바 변수와 관련된 주요 키워드 정리 (0) | 2024.10.19 |
---|---|
[Java] 생명 주기와 접근 범위에 따른 변수의 종류 (0) | 2024.10.18 |
[Java] Class - Scanner(스캐너) (0) | 2024.01.05 |
[Java] 조건문 - 삼항 연산자(ternary operator) (0) | 2024.01.04 |