ArrayList 구현 코드

한시삼십사분·2022년 1월 2일

자료구조 JAVA

목록 보기
6/16
post-thumbnail

List interface


public interface List<E> {
	/**
	 * 리스트에 값 추가
	 * @param value: 리스트에 추가할 값
	 * @return 중복을 허용하지 않을 경우 값이 중복된다면 false, 즁복 되는 값이 없다면 true return
	 */
	boolean add(E value);
	
	/**
	 * 리스트의 특정 위치에 값 추가
	 * @param index: 원하는 index
	 * @param value: 추가하려는 값
	 */
	void add(int index, E value);
	
	
	/**
	 * 특정 위치의 요소를 삭제
	 * @param index: 삭제할 값의 index
	 * @return: 삭제한 값을 반환
	 */
	E remove(int index);
	
	/**
	 * 특정 값을 갖는 요소 삭제
	 * @param value: 삭제할 요소의 값
	 * @return:삭제할 요소가 없거나 실패하면 false, 삭제에 성공하면 true return
	 */
	boolean remove(Object value);
	
	/**
	 * 특정 index의 값을 return
	 * @param index: 원하는 index
	 * @return: 해당 index의 원소
	 */
	E get(int index);
	
	/**
	 * 특정 index의 요소의 값을 변경
	 * @param index: 값을 변경하고자 하는 요소의 index
	 * @param value: 변경하고자 하는 값
	 */
	void set(int index, E value);
	
	/**
	 * 리스트가 특정 값을 갖는 요소가 있는지 확인
	 * @param value: 검사하고자 하는 특정 값
	 * @return: 있으면 true 없으면 false를 반환
	 */
	boolean contains(Object value);
	

	/**
	 * 특성 요소의 index를 반환
	 * @param value: 찾고자 하는 요소의 값
	 * @return: 해당 요소의 index, 해당 요소가 리스트에 없을 때는 -1 return
	 */
	int indexOf(Object value);
	
	/**
	 * 리스트의 크기 반환
	 * @return 리스트 크기 return
	 */
	int size();
	
	/**
	 * 리스트가 비어있는지 검사
	 * @return 비어있으면 true, 안비어있으면 false return
	 */
	boolean isEmpty();
	
	/**
	 * 리스트 초기화
	 */
	void clear();
}

ArrayList class

import java.util.Arrays;

public class ArrayList<E> implements List<E> {
	private static final int DEFAULT_CAPACITY = 10;
	private static final Object[] EMPTY_ARRAY = {};
	
	private int size;
	
	Object[] array;
	
	//셍성자1: 초기 공간 할당 x
	public ArrayList() {
		this.array = EMPTY_ARRAY;
		this.size = 0;
	}
	
	//생성자2: 초기 공간 할당 o
	public ArrayList(int capacity) {
		this.array = new Object[capacity];
		this.size = 0;
	}
	
	
	private void resize() {
		int curr_capacity = array.length;
		
		if(Arrays.equals(array, EMPTY_ARRAY)){
			array = new Object[DEFAULT_CAPACITY];
			
			return ;
			
		}
		
		if(curr_capacity == size) {
			int new_capacity = 2*curr_capacity;	
			array = Arrays.copyOf(array, new_capacity);
			return ;
		}
		
		if (size < (curr_capacity / 2)) {
			int new_capacity = curr_capacity / 2;
			array = Arrays.copyOf(array, Math.max(new_capacity, DEFAULT_CAPACITY));
			return ;
		}
	}
	
	
	@Override
	public boolean add(E value) {
		addLast(value);
		return true;
	}
	
	public void addLast(E value) {
		if(size == array.length) {
			resize();
		}
		this.array[size] = value;
		size++;
	}
	
	@Override
	public void add(int index, E value) {
		
		if(index<0 || index>=size) {
			throw new IndexOutOfBoundsException();
		}
		
		if(index == size) {
			addLast(value);
		}
		
		else {
			if(size == array.length) {
				resize();
			}
			
			for(int i = size; i>index; i--) {
				array[i] = array[i-1];
			}
			
			array[index] = value;
			size++;
		}
	}
	
	public void addFirst(E value) {
		add(0,value);
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public E get(int index) {
		if(index<0 || index>=size) {
			throw new IndexOutOfBoundsException();
		}
		return (E) array[index];  //타입캐스팅
	}
	
	
	@Override
	public void set(int index, E value) {
		if(index<0 || index>=size) {
			throw new IndexOutOfBoundsException();
		}
		else
			array[index] = value;
	}
	
	@Override
	public int indexOf(Object value) {
		for(int i=0; i<size; i++) {
			if(array[i].equals(value)) {  //객체간 비교할 때 == 연산자로 비교하면 주소를 비교하는 것임!
				return i;
			}
		}
		return -1;		
	}
	
	//찾고자 하는 index가 배열의 끝부분과 가깝다 판단하면 뒤에서부터 찾는 것이 효율적임
	public int LastindexOf(Object value) {
		for(int i=size-1; i>=0; i--) {
			if(array[i].equals(value)) {  //객체간 비교할 때 == 연산자로 비교하면 주소를 비교하는 것임!
				return i;
			}
		}
		return -1;	
	}
	
	public boolean contains(Object value) {
		if(indexOf(value) > -1)
			return true;
		else
			return false;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public E remove(int index) {
		if(index<0 || index>=size) {
			throw new IndexOutOfBoundsException();
		}
		E element = (E) array[index];
		
		for(int i=index; i<size-1; i++) {
			array[index] = array[index+1];
		}
		array[size-1] = null;
		size --;
		
		return element;
	}
	
	@Override
	public boolean remove(Object value) {
		int index = indexOf(value);
		if(index == -1) {
			return false;
		}
		remove(index);
		return true;
	}
	
	@Override
	public int size() {
		return size;
	}
	
	@Override
	public boolean isEmpty() {
		if(array.equals(EMPTY_ARRAY))
			return true;
		else
			return false;
		
		/*
		 * return size == 0 <- 이렇게 쓰면 더 간단함
		 */
	}
	
	@Override
	public void clear() {
		for(int i=0; i<size; i++) {
			array[i] = null;
		}
		size = 0;
		resize();
	}
	
	
}

https://st-lab.tistory.com/161?category=856997
내가 직접 코딩해보고 사이트를 확인하여 수정하는 방법으로 구현을 진행했음

profile
인간은 망각의 동물이라지만 이건 너무한 거 아니냐고

0개의 댓글