記錄

JAVA) 컬렉션 프레임워크(Collection Framework) 본문

Computer language/JAVA

JAVA) 컬렉션 프레임워크(Collection Framework)

surhommejk 2018. 2. 9. 11:43

<그림 1>




ArrayList ac Vector 차이


둘이 결정적으로 다른 점은 동기화Syncronized 되어있냐 아니냐의 차이이다.


ArrayList는 동기화가 되어있지 않아 멀티 스레드로 동시 접근이 가능하다. 따라서 여러곳에서 동시에 데이터를 막 바꿀 수 있는데 그만큼 속도가 빠르다. 주로 웹에서 사용하는 JAVA의 특성상 멀티 스레드로 동시 작업이 가능한 어레이리스트가 더 선호되는 게 아닌가 한다.


반대로 Vector는 동기화가 되어있어서 좀 더 데이터를 바꾸는것에 안전하지만 한번에 한 스레드밖에 접근을 못한다.


제네릭스를 사용할 수 있는건 둘이 동일하다. 딱 동기화가 되어있냐 아니냐의 차이정도만 알면 될것같다.


출처 : https://blog.naver.com/slayra/221201814398



Vector

/** * Appends the specified element to the end of this Vector. * * @param e element to be appended to this Vector * @return {@code true} (as specified by {@link Collection#add}) * @since 1.2 */ public synchronized boolean add(E e) {        <-- 실행중일때 다른 스레드에서 접근 방지! modCount++;                                   (synchronized) ensureCapacityHelper(elementCount + 1);       멀티스래드 상황에서 A 스래드가 add() 호출시 elementData[elementCount++] = e;              B 스래드는 A 스래드에서 호출된 add()가 끝나기전에 return true;                                  add()를 호출할 수 없다 }


ArrayList

    /**
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacity(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }


출처: okky.kr/article/442436





<그림 2>



참고: <그림 1>의 interface 부분만 확대한 것이 <그림 2>




public interface Iterable<T>

Implementing this interface allows an object to be the target of the "foreach" statement.

참고) iterate :  to say or do again; repeat


>> implements시 "foreeach"문을 가능하게 만들어준다


public interface Collection<E>

extends Iterable<E>

The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The JDK does not provide any direct implementations of this interface: it provides implementations of more specific subinterfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired.


>> 컬렉션 구조의 뿌리와 같은 interface이다. 여기서 말하는 컬렉션이란 object(또는 element라고도 할 수 있다)의 그룹이라고 할 수 있다. 컬렉션들 중에서는 각 요소를 복사할 수 있게 하는 것도 있고 복사 기능은 없는 것도 있다. 그리고 또 컬렉션들 중에서는 정렬된(인덱스 부여를 의미하는 것으로 보인다) 컬렉션이 있고 그렇지 않은 컬렉션(set 과 같은 것들로 추정된다)도 있다.... (중략)






ArrayList vs LinkedList




ArrayList


장점: 구조가 간단하고 데이터 읽는데 걸리는 시간(접근시간)이 빠르다


단점:

1) 크기를 변경할 수 없다

크기가 바뀌게 되면 원래 주소값에서 크기를 키우는 것이 아니라 아예 새로운 배열 객체를 생성하고 모든 데이터가 그곳으로 이사하게 되는 것이다. 이는 비용이 큰 작업이라고 할 수 있다.(메모리 자원의 효율성이 떨어진다는 의미)


여기서 주목할 점은 .add를 한다고 해서 무조건 새로운 객체를 만들고 전체가 이사를 하는 것은 아니라는 뜻이다. 기존의 크기에서 하나씩 밀어내어서 처리가 가능하다면 굳이 이사를 하진 않고 기존 크기 내에서 하나씩 밀어내는 것이 이뤄진다.


2) 비순차적인 데이터 추가, 삭제에 시간이 많이 걸린다

순차적인 데이터 추가나 삭제(양쪽 끝에서 이뤄지는 수정)는 빠르지만 중간에 있는 데이터의 추가나 삭제하기 위해서는 시간이 오래 걸린다.(많은 데이터를 옮겨야 하기 때문이다)


참고:

ArrayList li = new ArrayList(); 로 생성시에 li에 들어가는 default type은 'Object' 타입이다.

따라서 특정 클래스를 넣거나 빼길 원한다면 casting을 해주어야 한다.

들어갈때부터 타입 설정을 원한다면 Generic 설정을 꼭 해주어야 한다.


ex) ArrayList<Emp> li = new ArrayList<Emp>();





LinkedList















'Computer language > JAVA' 카테고리의 다른 글

JAVA) ' .equlas ' 와 ' == ' 의 차이  (0) 2018.02.13
JAVA) Down Casting  (0) 2018.02.09
JAVA) 메모리 구조 -2 (수정중)  (0) 2018.02.08
JAVA) 메모리 구조 -1  (0) 2018.02.08
JAVA) String과 주소값  (0) 2018.02.08
Comments