[자료구조] ArrayList (JAVA)

Coastby·2022년 8월 15일
0

List

리스트는 배열과 비슷한 자바의 자료형으로 배열보다 편리한 기능을 많이 가지고 있다.

배열과의 가장 큰 차이는 크기가 정해져 있지 않고 동적으로 변한다는 점이다. 동적으로 자료형의 갯수가 가변한는 상황이라면 List를 사용하는 것이 유리하다.

💡 List 자료형에는 ArrayList, Vector, LinkedList 등의 List 인터페이스를 구현한 자료형이 있다. 여기서 말하는 자료형은 인터페이스이다.

ArrayList

List 자료형 중 가장 간단한 형태의 자료형이다.

import java.util.ArrayList

ArrayList 를 사용하기 위해서는 java.util.ArrayList를 import 해야한다.

○ 생성

투구 스피드를 저장하는 리스트를 생성한다.

💡 자바는 J2SE 5.0 버전 이후부터 객체를 포함하는 자료형도 어떤 객체를 포함하는지에 대해서 명확하게 표현할 것을 권고하고 있다. 인텔리제이에서 제네릭스 없이 `ArrayList pitches = new ArrayList();` 코딩하면 명확한 타입을 명시하라고 경고가 표시될 것이다.
  • add 이용하기
ArrayList<String> pitches = new ArrayList<>();
pitches.add("138");
pitches.add("129");
pitches.add("142");
  • 데이터가 존재하는 경우
public class Sample {
    public static void main(String[] args) {
        String[] data = {"138", "129", "142"};  // 이미 투구수 데이터 배열이 있다.
        ArrayList<String> pitches = new ArrayList<>(Arrays.asList(data));
        System.out.println(pitches);  // [138, 129, 142] 출력
    }
}
  • 바로 전달해서 생성하기
public class Sample {
    public static void main(String[] args) {
        ArrayList<String> pitches = new ArrayList<>(Arrays.asList("138", "129", "142"));
        System.out.println(pitches);
    }
}

○ add

첫 번째 위치에 “133”을 삽입하고 싶다면 아래와 같이 삽입할 위치를 파라미터로 넘겨주어야 한다.

pitches.add(0, "133");

○ get

ArrayList의 get 메소드를 이용하면 특정 인덱스에 있는 값을 리턴한다.

2번째 투구 스피드를 출력하고 싶다면 다음과 같다.

System.out.println (pitches.get(1));

○ size

size 메소드는 ArrayList의 크기를 리턴한다.

System.out.println (pitches.size());

○ contains

contains 메소드는 리스트 안에 해당 항목이 있는지를 판별하여 그 결과를 boolean으로 리턴한다.

Sysstem.out.println (pitches.contains("133");

//result
//해당 항목이 있으므로
true

○ remove

https://hianna.tistory.com/564

remove 메소드는 입력 파라미터에 따라 2가지 방식이 있다.

  1. remove(Object o) : 객체에 해당되는 첫번째 항목을 삭제하고 삭제한 결과 (true, false)를 리턴한다. 삭제할 값이 없으면 false를 리턴한다.
System.out.println (pitches.remove("133"));

//result
true
  1. remove(int index) : 해당 인덱스 항목을 삭제하고 삭제된 항목을 리턴한다. 메소드의 파라미터로 Int가 전달되면 해당 index의 값이 삭제된다.
ArrayList<Integer> odd = new ArrayList<>(Arrays.asList(1, 3, 5, 7, 9));
System.out.println (odd.remove(9));

//result
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 9 out of bounds for length 5

index가 아니라 리스트의 요소인 9를 삭제하고 싶다면 Integer 객체를 전달해야 한다.

ArrayList<Integer> odd = new ArrayList<>(Arrays.asList(1, 3, 5, 7, 9));
odd.remove(Integer.valueOf(9));
System.out.println (odd);

👉 특정값 전체를 삭제하기

value가 9인 항목을 모두 지우려면 while을 이용한다.

ArrayList<Integer> odd = new ArrayList<>(Arrays.asList(1, 3, 5, 7, 9, 9, 9));
while (odd.remove(Integer.valueOf(9))) {};
System.out.println (odd);

//result
[1, 3, 5, 7]

○ String.join

String.join (”구분자”, 리스트객체) 와 같이 사용하여 리스트의 각 요소에 “구분자"를 삽입하여 하나의 문자열로 만들 수 있다. 문자열 배열에도 사용할 수 있다. (Java 8 버전부터 사용가능)

public class Sample {
    public static void main(String[] args) {
        ArrayList<String> pitches = new ArrayList<>(Arrays.asList("138", "129", "142"));
        String result = String.join(",", pitches);
        System.out.println(result);  // 138,129,142 출력
    }
}

○ 리스트 정렬하기

public class Sample {
    public static void main(String[] args) {
        ArrayList<String> pitches = new ArrayList<>(Arrays.asList("138", "129", "142"));
        pitches.sort(Comparator.naturalOrder());  // 오름차순으로 정렬
        System.out.println(pitches);  // [129, 138, 142] 출력
    }
}
  • 오름차순(순방향) 정렬 - Comparator.naturalOrder()
  • 내림차순(역방향) 정렬 - Comparator.reverseOrder()
profile
훈이야 화이팅

0개의 댓글