Algorithm/알고리즘 이론

ArrayList 코드

Razelo 2020. 12. 15. 15:51

 

package algorithm;

public class ArrayList {
	private int size = 0;
	private Object[] elementData = new Object[100];
	
	public boolean addFirst(Object element) {
		return add(0,element);
	}	
	public boolean addLast(Object element) {
		elementData[size]  = element;
		size++;
		return true;
	}
	public boolean add(int index,Object element) {
		for(int i = size-1;i>=index;i--) {
			elementData[i+1] = elementData[i];
		}
		elementData[index] = element;
		size++;
		return true;
	}
	
	public String toString() {
		String str = "[";
		for(int i = 0;i<size;i++) {
			str+= elementData[i];
			if(i<size -1) {
				str+=",";
			}
			
		}
		return str+"]";
	}
	public Object remove(int index) {
		Object removed = elementData[index]; 
		for(int i = index+1;i<=size-1;i++) {
			elementData[i-1] = elementData[i];
		}
		size--;
		elementData[size] = null;
		return removed;
	}
	public Object removeFirst() {
		return remove(0);
	}
	public Object removeLast() {
		return remove(size-1);
	}
	public Object get(int index) {
		return elementData[index];
	}
	public int size() {
		return size;
	}
	public int indexOf(Object o) {
		for(int i = 0;i<size;i++) {
			if(o.equals(elementData[i])) {
				return i;
			}
		}
		return -1;
	}
	public ListIterator listIterator() {
		return new ListIterator();
	}
	class ListIterator{
		private int nextIndex = 0;
		
		public boolean hasNext() {
			return nextIndex<size();
		}
		public Object next() {
			return elementData[nextIndex++];
		}
		public Object previous() {
			return elementData[--nextIndex];
		}
		public boolean hasPrevious() {
			return nextIndex > 0;
		}
		public void add(Object element) {
			ArrayList.this.add(nextIndex++,element);
		}
		public void remove() {
			ArrayList.this.remove(nextIndex-1);
			nextIndex--;
		}
	}
}

ArrayList 의 코드 

 

밑에 방식으로 사용하면 된다. 

 

package algorithm;

public class ArrayMain {

	public static void main(String[] args) {
		ArrayList numbers = new ArrayList();
		numbers.addLast(10);
		numbers.addLast(20);
		numbers.addLast(30);
		numbers.addLast(40);
		
//		for(int i = 0;i<numbers.size();i++) {
//			System.out.println(numbers.get(i));
//		}
//		ArrayList.ListIterator li= numbers.listIterator();
//		while(li.hasNext()) {
//			System.out.println(li.next());
//		}
		
//		ArrayList.ListIterator li= numbers.listIterator();
//		while(li.hasNext()) {
//			System.out.println(li.next());
//		}
//		while(li.hasPrevious()) {
//			System.out.println(li.previous());
//		}
		
		ArrayList.ListIterator li= numbers.listIterator();
		while(li.hasNext()) {
			int number = (int)li.next();
			if(number == 30) {
				li.add(35);
			}
		}
		System.out.println(numbers);
		
	}
}
반응형

'Algorithm > 알고리즘 이론' 카테고리의 다른 글

알고리즘 설명해주는 블로그  (0) 2020.12.24
DoublyLinkedList 코드  (0) 2020.12.17
LinkedList 코드  (0) 2020.12.17
리스트와 배열의 차이  (0) 2020.12.15
힙정렬 코드  (0) 2020.12.14