ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Java API 분석__Class ArrayList
    개발입문/자료구조 2017. 7. 24. 15:35

    ArrayList


     
    public class ArrayList<E>
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, Serializable

    Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)




    - Array + List  리사이징 가능한 배열 

    - 단, 배열[인덱스] 가 아니라 메소드를 통해서 객체에 접근한다. 

    - 원소 null 허용

    - thread - unsafe




    public void checkArrayList() {

    ArrayList list1 = new ArrayList();

    list1.add(new Object());

    list1.add("ArrayListSample");

    list1.add(new Double(1));

    }

    /*

     * ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized.

     */


    (!) 를 누르면 Type un-safety 를 지적한다.

    ArrayList 에 들어올 원소들의 Type 을 명시하기를 요구한다.

    Object 또는 Generic 또는 완전 구체적으로 DTO 객체 하나를 명시할 수 있다.  





    Constructor 생성자


    public void checkArrayList() {

    ArrayList<String> list1 = new ArrayList<String>();

    list1.add("ArrayListSample");

    }


    ArrayList 는 한가지 종류의 객체만 저장한다. DTO 라는 객체를 하나 만들어서 담는 것이 좋다.  

    컬렉션 관련 클래스들의 객체를 선언할 때에는 제네릭을 사용하여 선언하는 것을 권장한다. Type-safety



    ArrayList<String> list2 = new ArrayList<String>(100);


    ArrayList 객체를 선언할 때 매개변수를 넣지 않으면 ArrayList 의 디폴트 크기를 10이다. 따라서, 10개 이상의 데이터가 들어가면 크기를 늘이는 작업이 ArrayList ㅐ부에서 자동으로 수행된다. 이러한 작업이 수행되면 애플리케이션의 성능에 영향을 주게된다. 만약 저장되는 데이터의 크기가 어느정도 예측 가능하다면 다음과 같이 예측한 초기값을 위와같이 지정할 것을 권장한다. 



    ArrayList<String> list = new ArrayList<String>();

    ArrayList<String> list2 = list;

    list.add("Ooops");


    list2 변수에 list 컬렉션의 주소가 복사되었다. (즉 list2 또한 list와 동일한 객체를 가리킨다.)

    따라서, 하나의 Collection 관련 객체를 복사할 일이 있을 때에는ArrayList(Collection<? extends E> c) 생성자를 사용하거나, addAll() 메소드를 사용할 것을 권장한다.





    메소드


    public boolean addAll(Collection<? extends E> c)

    addAll 의 인자로 들어온 컬렉션에 대해 해당 컬렉션의 Iterator 를 통해 list2 뒤에 추가 (append) 한다.

    컬렉션 구현체 간 데이터를 주고받을 수 있는 메소드


    ArrayList<String> list = new ArrayList<String>();

    list.add("A"); list.add("B"); list.add("C");


    ArrayList<String> list2 = new ArrayList<String>();

    list2.add("a");

    list2.addAll(list);    //a A B C




    public <T> T[] toArray(T[] a)

    bridge between array-based and collection-based APIs

    배열과 컬렉션 구현체간 데이터를 주고받을 수 있는 가교 역할을 하는 메소드


    String[] tempArr = new String[2];

    for (String temp: tempArr) {

    System.out.print(temp + " ");

    }                //null null

    String[] strList = list.toArray(tempArr);

    for (String temp: strList) {

    System.out.println(temp);

    }                //A B C D E


    for (String temp: tempArr) {

    System.out.println(temp);

    }                //null null


    만약 tempArr.length() 가 list.size()보다 일치 or 컸다면 

    tempArr 도 list의 원소로 채워진다. 


    그러나 list.size()보다 작다면 

    tempArr 는 그대로 두고, 내부적으로 tempArr 의 형을 딴 새로운 배열을 생성한다. 

    반환값 strList 는 tempArr 의 타입과 list 의 원소 사이즈를 가진 배열이다. 



    public E set(int index, E element)

    - 지정된 인덱스에 지정된 원소로 변경한다.

    - 변경 전 원소를 반환한다.


    ArrayList<String> list = new ArrayList<String>();

    list.add("A"); list.add("B"); list.add("C");

    list.add("D"); list.add("E"); list.add("A");

    System.out.println("Previous element: " + list.set(5"F"));

    System.out.println("Changed element: " + list.get(5));





    List 는 Ordered!

    - 인덱스(순서)로 접근할 수 도 있고!

    - 인자로 제공된 객체랑 일치하는 객체로 조회/삭제할 수 도 있다.

    public E remove(int index)
    - 지정된 인덱스의 원소를 삭제한다.
    - 지정된 인덱스 다음에 있는 (subsequent) 원소들을 한개씩 앞으로 옮긴다.
    - 삭제한 원소를 반환한다.



    public boolean remove(Object o)

    - 리스트에서 지정된 객체와 일치하는 가장 첫번째 원소를 삭제한다.

    - 다음에 있는 원소들을 한개씩 앞으로 옮긴다.

    - 삭제한 원소가 있을 경우 true, 아니면 false 를 반환한다.


    public boolean removeAll(Collection<?> c)

    - 리스트에서 지정된 객체와 일치하는 모든 원소를 삭제한다.

    - 다음에 있는 원소들을 한개씩 앞으로 옮긴다.

    - 삭제한 원소가 있을 경우 true, 아니면 false 를 반환한다.



    public void trimToSize()

    - ArrayList 객체 공간의 크기(capacity) 를 데이터의 개수(size) 만큼 줄인다. 

    - 만약 ArrayList 의 객체를 원격으로 전송하거나 파일로 저장하는 일이 있을 때 호출하면, 데이터의 크기를 줄일 수 있다는 장점이 있다. 




    Make it Synchronized

    ArrayList 는 thread-unsafe 하다. (Vector는 thread-safe하다) 

    ArrayList 를 thread-safe 하도록 속성을 지정해주고 싶다면.


    Class Collections 의 다음 static 메소드를 통해서 구현하면 된다. 

    public static <T> List<T> synchronizedList(List<T> list)

    List list = Collections.synchronizedList(new ArrayList());


    synchronized (list) {

    Iterator i = list.iterator(); 

    while (i.hasNext()) {

    foo(i.next()); 

    }

    }

    // Must be in synchronized block


    '개발입문 > 자료구조' 카테고리의 다른 글

    Java API 분석__Class Vector  (0) 2017.07.25
    Java API 분석__Class Stack  (0) 2017.07.24
    Java API 분석__ Interface List  (0) 2017.07.24
    Java API 분석__ Interface Collection  (0) 2017.07.24
    05. 순차 자료구조 방식  (0) 2017.07.04

    댓글

Designed by Tistory.