본문 바로가기
Programming/Java

[Java] Class ArrayList<E> 사용법 정리

by 우공80 2022. 11. 1.
728x90

ArrayList 사용법 정리

ArrayList 란?

ArrayList는 Java에서 제공하는 컬렉션 프레임워크입니다. 컬렉션 프레임워크는 Java의 자료구조를 표현하고 조작하기 위한 구조를 정의한 것입니다. LIst, Set, Map 등의 Interface가 정의되어있고, 이를 구현한 클래스가 있습니다.

오늘은 그중에서 ArrayList를 알아보겠습니다. ArrayList는 이름과 같이 배열을 List로 구현한 것입니다.
Cos Pro 1급 시험을 준비하고 있는데, 배열을 다룰 때 매번 함수를 정의하기가 불편해서 ArrayList를 쓰는 법을 정리해 두려고 합니다.

주요 메서드

아래와 같이 주요 메서드와 결과를 정리해 보았습니다.

0. 객체 생성

ArrayList 객체는 아래와 같이 생성합니다. 컬렉션 프레임워크는 제네릭 타입으로 되어있는데,
제네릭은 클래스 선언 시에만 제네릭이고, 객체 생성할 때는 타입을 지정해 주어야 합니다. 
저는 정수를 담기 위해 Integer로 지정했습니다. 이때 new 연산자 쪽에는 공란으로 두어도 무방합니다.

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


1. public boolean add(E e)

add()는 ArrayList에 요소를 추가하는 메서드입니다.
아래와 같이 ArrayList의 마지막 위치에 추가가 됩니다. 

참고로 ArrayList는 toString() 메서드를 쓰면 배열을 문자열로 반환합니다.

//public boolean add(E e)
scores.add("100");
scores.add("300");
scores.add("200");
scores.add("500");
scores.add("400");
scores.add("700");
System.out.println("1. scores: "+scores.toString()+" scores 출력");

 

1. scores: [100, 300, 200, 500, 400, 700] scores 출력

add()는 index와 함께 사용할 수 있는데요. index를 지정하게 되면, index 위치에 값을 넣고, 원래 값들은 한 칸씩 뒤로 밀려나게 됩니다.

//public void add(int index, E element) index 위치에 추가하고 원래 값은 뒤로 밀려남
scores.add(0,"600");
//toString();
System.out.println("1. scores: "+scores.toString()+" add-index:0에 "600"을 추가");

 

1. scores: [600, 100, 300, 200, 500, 400, 700] add-index:0에 600을 추가

 

2. public E set(int index, E element)

set()은 index 위치에 값을 넣는 메서드입니다. add()에 index 넣는 것과 무슨 차이가 있나 싶은데요.
add()는 값을 넣으면 배열이 한 칸씩 뒤로 밀리는데, set은 index 위치에 값을 대체하고 다른 값들은 그대로 있다는 것이 다릅니다.

//public E set(int index, E element) index 위치의 값을 대체함
scores.set(0, "800");
System.out.println("2. scores: "+scores.toString()+" set-index:0을 "800"으로 대체");

 

2. scores: [800, 100, 300, 200, 500, 400, 700] set-index:0을 800으로 대체


3. public void sort(Comparator<? super E> c)

정렬 방법입니다. Collections의 static 메서드입니다. 다른 메서드와 사용방법이 다르니 잘 외워두는 게 좋겠습니다.

//public void sort(Comparator<? super E> c)
Collections.sort(scores);
System.out.println("3. scores: "+scores.toString()+" 오름차순 정렬");
Collections.sort(scores,Collections.reverseOrder());
System.out.println("3. scores: "+scores.toString()+" 내림차순 정렬");

 

3. scores: [100, 200, 300, 400, 500, 700, 800] 오름차순 정렬
3. scores: [800, 700, 500, 400, 300, 200, 100] 내림차순 정렬


4. public E remove(int index)

remove()는 주어진 index의 값을 제거합니다. 그리고 제거한 값을 반환해줍니다.

//public E remove(int index)
int removeScore=scores.remove(0);
System.out.println("4. scores: "+scores.toString()+"remove-index:0을 삭제");
System.out.println("4. removeScore(remove의 반환값): "+removeScore);

 

4. scores: [700, 500, 400, 300, 200, 100]remove-index:0을 삭제
4. removeScore(remove의 반환값): 800


5. public boolean remove(Object o)

remove() 삭제하고자 하는 객체를 넣어주면 됩니다. 단, 이때 ArrayList가 Integer인 경우에는 값을 넣더라도 index로 인식하므로 out of index 오류가 발생합니다. 

//public boolean remove(Object o)
scores.remove("400");
System.out.println("5. scores: "+scores.toString()+"remove-값 400을 삭제");

 

5. scores: [700, 500, 300, 200, 100]remove-값 400을 삭제


6.  public int size()

배열의 length처럼 ArrayList의 길이를 반환합니다.

//public int size()
System.out.println("6. size of scores: "+scores.size());

 

6. size of scores: 5


7. public E get(int index)

index 위치의 값을 가져옵니다.

//public E get(int index)	
System.out.println("7. scores[1]: "+scores.get(1)+" get-index의 값을 가져오기");

 

7. scores[1]: 500 get-index의 값을 가져오기


8. public int indexOf(Object o)

특정 값의 위치(index)를 반환합니다.

//public int indexOf(Object o)
System.out.println("8. index of 300 in scores: "+scores.indexOf(300));

 

8. index of 300 in scores: 2


9. public boolean contains(Object o)

ArrayList가 특정 값을 가지고 있는지 여부만 판단합니다. 

//public boolean contains(Object o)
System.out.println("9. whether score contains 300: "+scores.contains("300"));

 

9. whether score contains 300: true


10. public boolean isEmpty()

ArrayList가 비어있는지 확인 합니다.

//public boolean isEmpty()
System.out.println("10. whether score is empty: "+scores.isEmpty());

 

10. whether score is empty: false


11. public Object clone()

ArrayList를 복제합니다.

//public Object clone()
ArrayList<Integer> scores2 = (ArrayList<Integer>) scores.clone();
System.out.println("12. scores2: "+scores2.toString()+" clone-score 복제");

 

11. scores2: [700, 500, 300, 200, 100] clone-score 복제


12. public boolean removeAll(Collection<?> c)

ArrayList의 모든 값을 삭제합니다.

//public boolean removeAll(Collection<?> c)
scores2.removeAll(scores2);
System.out.println("12. scores2 remove all: "+scores2.toString());

 

12. scores2 remove all: []

 

728x90

 

전체 코드

import java.util.*;

public class ArrayListTest{

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        //public boolean add(E e)
        ArrayList<String> scores = new ArrayList<>();
        scores.add("100");
        scores.add("300");
        scores.add("200");
        scores.add("500");
        scores.add("400");
        scores.add("700");
        System.out.println("1. scores: "+scores.toString()+" scores 출력");

        //public void add(int index, E element) index 위치에 추가하고 원래 값은 뒤로 밀려남
        scores.add(0,"600");

        //toString();
        System.out.println("1. scores: "+scores.toString()+" add-index:0에 600을 추가");

        //public E set(int index, E element) index 위치의 값을 대체함
        scores.set(0, "800");
        System.out.println("2. scores: "+scores.toString()+" set-index:0을 800으로 대체");

        //public void sort(Comparator<? super E> c)
        Collections.sort(scores);
        System.out.println("3. scores: "+scores.toString()+" 오름차순 정렬");
        Collections.sort(scores,Collections.reverseOrder());
        System.out.println("3. scores: "+scores.toString()+" 내림차순 정렬");

        //public E remove(int index)
        String removeScore=scores.remove(0);

        //public boolean remove(Object o)
        System.out.println("4. scores: "+scores.toString()+"remove-index:0을 삭제");
        System.out.println("4. removeScore(remove의 반환값): "+removeScore);

        scores.remove("400");
        System.out.println("5. scores: "+scores.toString()+"remove-값 400을 삭제");


        //public int size()
        System.out.println("6. size of scores: "+scores.size());

        //public E get(int index)
        System.out.println("7. scores[1]: "+scores.get(1)+" get-index의 값을 가져오기");

        //public int indexOf(Object o)
        System.out.println("8. index of 300 in scores: "+scores.indexOf("300"));

        //public boolean contains(Object o)
        System.out.println("9. whether score contains 300: "+scores.contains("300"));

        //public boolean isEmpty()
        System.out.println("10. whether score is empty: "+scores.isEmpty());

        //public Object clone()
        ArrayList<String> scores2 = (ArrayList<String>) scores.clone();
        System.out.println("11. scores2: "+scores2.toString()+" clone-score 복제");

        //public boolean removeAll(Collection<?> c)
        scores2.removeAll(scores2);
        System.out.println("12. scores2 remove all: "+scores2.toString());
    }
}
//출력
1. scores: [100, 300, 200, 500, 400, 700] scores 출력
1. scores: [600, 100, 300, 200, 500, 400, 700] add-index:0에 600을 추가
2. scores: [800, 100, 300, 200, 500, 400, 700] set-index:0을 800으로 대체
3. scores: [100, 200, 300, 400, 500, 700, 800] 오름차순 정렬
3. scores: [800, 700, 500, 400, 300, 200, 100] 내림차순 정렬
4. scores: [700, 500, 400, 300, 200, 100]remove-index:0을 삭제
4. removeScore(remove의 반환값): 800
5. scores: [700, 500, 300, 200, 100]remove-값 400을 삭제
6. size of scores: 5
7. scores[1]: 500 get-index의 값을 가져오기
8. index of 300 in scores: 2
9. whether score contains 300: true
10. whether score is empty: false
11. scores2: [700, 500, 300, 200, 100] clone-score 복제
12. scores2 remove all: []
728x90

댓글