Generic한 리스트 클래스를 만들어보자.
리스트
여러 개의 데이터를 저장하고
임의의 위치에 새로운 데이터를 추가하거나
데이터의 삭제가 가능하고
임의의 위치의 데이터를 읽을 수 있고,
용량에 제한이 없는
...
클래스
사용 예
예를 들어 String들을 저장하려면
MyArrayList<String> myList = new MyArrayList<String>();
생성된 리스트에 String 추가
myList.add("Bashful");
myList.add("Awful");
myList.add("Jumpy");
추가한 순서대로 저장된다.
myList.add(2, "Doc");
2번위치에 (배열의3번째칸) 에 추가하라 기존에있던 데이터를 한칸 씩 뒤로 밈
myList.remove(1);
1번위치 값을 삭제하고 빈 공간을 앞으로 땡겨온다.
myList.set(2,"Sneezy");
2번위치를 덮어쓰는 기능.
String dwarf = myList.get(2)
인덱스를 매개변수로 값을 리턴하는기능
int index = myList.indexOf("Sneezy");
인덱스 값을 리턴해준다.
없다면 -1 리턴
package section5;
import java.util.Arrays;
public class MyArrayList<T> {
private static final int INIT_CAPACITY = 10;
private T[] theData;
private int size;
private int capacity = INIT_CAPACITY;
public MyArrayList() {
theData = (T []) new Object [INIT_CAPACITY];
size = 0;
}
public void add(int index, T anEntry) {
if(index < 0 || index > size) {
throw new ArrayIndexOutOfBoundsException(index);
}
if(size >= capacity){
reallocate();
}
for(int i=size-1; i>=index; i--) {
theData[i+1] = theData[i];
}
theData[index] =anEntry;
size++;
}
private void reallocate() {
capacity *= 2;
theData = Arrays.copyOf(theData, capacity);
}
public void add(T anEntry) {
add(size, anEntry);
}
public int size() {
return size;
}
public int indexOf(T anEntry) {
for(int i =0; i<size; i++) {
if(theData[i].equals(anEntry)) {
return i;
}
}
return -1;
}
public T get(int index) {
if(index <0 || index >= size) {
throw new ArrayIndexOutOfBoundsException(index);
}
return theData[index];
}
public T set(int index, T newValue) {
if(index <0 || index >= size) {
throw new ArrayIndexOutOfBoundsException(index);
}
T oldValue = theData[index];
theData[index] = newValue;
return oldValue;
}
public T remove(int index) {
if(index < 0|| index >= size) {
throw new ArrayIndexOutOfBoundsException(index);
}
T returnValue = theData[index];
for(int i = index+1; i<size; i++) {
theData[i-1]=theData[i];
}
size--;
return returnValue;
}
}
'알고리즘 with 자바 > 자료구조' 카테고리의 다른 글
| 연결리스트의 개념과 기본연산 1 (0) | 2021.07.14 |
|---|---|
| Generic 프로그래밍과 Generics 3 (0) | 2021.07.13 |
| Generic 프로그래밍과 Generics 1 (0) | 2021.07.09 |
| 추상클래스와 인터페이스 3 (0) | 2021.07.07 |
| 추상클래스와 인터페이스 2 (0) | 2021.07.07 |