[Java] 자바 List(리스트) 인터페이스 선언, 정렬, 출력, 초기화 방법

자바 List는 Java Collections Framework의 핵심 구성 요소로, 요소를 저장하기 위해 다양하고 정렬된 컬렉션을 제공합니다. 그럼 아래에서 List에 대해서 더 자세히 알아보겠습니다. 자바 List의 선언, 출력, 정렬 방법에 대해서 알아보고, List를 구현한 ArrayList, LinkedList, Vector의 특징에 대해서 알아보겠습니다.


목차


자바 List 인터페이스

자바 List는 array의 한계 때문에 만들어진 자료형입니다.
자바 List와 array의 가장 큰 차이는 array는 사이즈가 고정되어 변경할 수 없습니다. 하지만 List사이즈가 고정되어 있지 않고 동적으로 변합니다.

자바 List를 사용하는 이유는??

  • 동적 크기 조절
    자바 List는 요소가 추가되거나 제거될 때 커지거나 줄어들 수 있습니다.
  • 손쉬운 요소 조작
    List의 어느 위치에서나 요소를 추가, 제거 또는 수정할 수 있습니다.
  • 반복을 위한 메소드를 제공
  • 제네릭 지원

자바 List 인터페이스 구현

List 구현

자바 List 인터페이스는 Java Collections Framework의 핵심 구성 요소로, 요소를 저장하기 위해 다양하고 정렬된 컬렉션을 제공합니다. List의 각 요소에는 색인(index)이 할당되어 위치에 따라 요소에 쉽게 액세스, 수정 또는 제거할 수 있습니다. List의 주요 특징 중 하나는 중복 요소를 허용한다는 것입니다.
그럼 아래에서 List 인터페이스의 공통 메소드와 ArrayList, LinkedList, Vector에 대해서 알아보겠습니다.


자바 List 인터페이스의 공통 메소드

  • add(E element): 지정된 요소를 List 끝에 추가
  • add(int index, E element): 지정된 인덱스에 지정된 요소를 추가하고 기존 요소를 이동합니다.
  • get(int index): 지정된 인덱스에 있는 요소를 검색
  • remove(int index): 인덱스에 있는 요소를 제거하고 반환하며 뒤에 있는 요소를 이동
  • size(): 요소의 를 반환
  • isEmpty(): List가 비어 있는지 확인하고 요소가 없으면 true를 반환
  • contains(Object o): 지정된 요소가 포함되어 있는지 확인하고, 발견되면 true를 반환
  • indexOf(Object o): 지정된 요소가 처음 나타나는 인덱스를 반환, 찾지 못하면 -1을 반환
  • clear(): 모든 요소를 ​​제거

ArrayList

ArrayList 데이터 추가 삭제

  • 내부적으로 동적 배열을 사용하여 요소를 저장
  • 색인(index)으로 요소를 검색할 때 빠른 액세스 시간(O(1))을 제공
  • 배열 크기 조정이 필요할 수 있으므로 요소를 삽입하거나 삭제할 때 성능이 느려집니다.
  • 동기화되지 않아 단일 쓰레드 환경에 더 적합합니다.

생성 및 초기화

import java.util.ArrayList;

// 빈 ArrayList 만들기 ArrayList
ArrayList<String> myArrayList = new ArrayList<>();

// 초기 사이즈를 지정해서 ArrayList 생성
ArrayList<Integer> numbersList = new ArrayList<>(10);

// ArrayList 생성 및 초기화
ArrayList<String> fruitsList = new ArrayList<>(Arrays.asList("Apple", "Orange", "Banana"));

요소 추가 및 제거


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

myArrayList.add("Element 1");
myArrayList.add("Element 2");
myArrayList.add("Element 3");

// Removing elements from the ArrayList
myArrayList.remove("Element 2"); // "Element 2" 제거
myArrayList.remove(0); // index가 0인 요소를 제거

요소에 엑세스

String firstElement = myArrayList.get(0); //  index 0에소 요소를 엑세스

int lastIndex = myArrayList.size() - 1; // 마지막 인덱스를 찾고
String lastElement = myArrayList.get(lastIndex); // 마지막 인덱스 요소를 엑세스

추가로 ArrayList에 대해서 더 궁금하시다면 클릭해주세요.


LinkedList

LinkedList

  • 이중 연결 목록 데이터 구조를 사용하여 요소를 저장합니다.
  • 목록의 시작 또는 중간에서 요소를 추가하거나 제거할 때 빠른 삽입 및 삭제(O(1)).
  • 색인으로 요소를 검색할 때 시작 또는 끝에서 목록을 탐색해야 하므로 액세스 시간(O(n))이 느려집니다.
  • ArrayList와 같이 동기화되지 않아 단일 스레드 환경에 더 적합합니다..

생성 및 초기화

import java.util.LinkedList;

// 빈 LinkedList 생성
LinkedList<String> myLinkedList = new LinkedList<>();

// LinkedList 생성 및 초기화
LinkedList<Integer> numbersList = new LinkedList<>(Arrays.asList(1, 2, 3));

요소 추가 및 제거


LinkedList<String> myLinkedList = new LinkedList<>();

myLinkedList.add("Element 1");
myLinkedList.add("Element 2");
myLinkedList.add("Element 3");

// Adding elements at the beginning of the LinkedList
myLinkedList.addFirst("First Element"); 
myLinkedList.addLast("Last Element");

// Removing elements from the LinkedList
myLinkedList.remove("Element 2"); // "Element 2" 삭제
myLinkedList.removeFirst(); // 첫 번째 요소 삭제
myLinkedList.removeLast(); // 마지막 요소 삭제

  • addFirst() : 첫 번째 요소로 추가
  • addLast() : 마지막 요소로 추가
  • removeFirst() : 첫 번째 요소 삭제
  • removeLast() : 마지막 요소 삭제

요소에 엑세스하기


String firstElement = myLinkedList.get(0); // index 0인 요소 엑세스

int lastIndex = myLinkedList.size() - 1; // 마지막 요소의 인덱스를 찾고
String lastElement = myLinkedList.get(lastIndex); // 마지막 요소 엑세스


Vector

  • ArrayList와 유사하지만 동기화되어 스레드로부터 안전합니다.
  • 추가된 동기화 오버헤드로 인해 성능이 느려집니다.
  • 스레드 안전성이 중요한 다중 스레드 환경에 적합합니다.
  • ArrayList보다 오래되었으며 동기화가 필요하지 않은 경우 일반적으로 ArrayList가 선호됩니다.

생성 및 초기화

import java.util.Vector;

// 빈 Vector 생성
Vector<String> myVector = new Vector<>();

// 초기 사이즈를 지정해서 Vector 생성
Vector<Integer> numbersVector = new Vector<>(10);

// Vector 생성 및 초기화
Vector<String> fruitsVector = new Vector<>(Arrays.asList("Apple", "Orange", "Banana"));

요소 추가 및 제거


Vector<String> myVector = new Vector<>();

//추가
myVector.add("Element 1");
myVector.add("Element 2");
myVector.add("Element 3");

// 제거
myVector.remove("Element 2"); // "Element 2" 제거
myVector.remove(0); // index 0인 요소를 제거

요소 엑세스

String firstElement = myVector.get(0); // index 0인 요소 엑세스

int lastIndex = myVector.size() - 1; // 마지막 요소의 인덱스를 찾고
String lastElement = myVector.get(lastIndex); // 마지막 요소 엑세스

자바 List 정렬, 검색, 출력


Comparable 정렬 및 출력

Comparable 인터페이스를 구현하고 compareTo() 메서드를 재정의하면 요소를 비교하고 정렬하는 방법을 정의할 수 있습니다.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Student> studentsList = new ArrayList<>();
        studentsList.add(new Student("John", 3.8));
        studentsList.add(new Student("Alice", 4.0));
        studentsList.add(new Student("Bob", 3.5));

        // 학생들을 GPA별로 분류(상위에서 최하위)

        Collections.sort(studentsList);

        //정렬된 학생 목록 출력
        for (Student student : studentsList) {
            System.out.println(student.getName() + " - GPA: " + student.getGpa());
        }
    }
}

class Student implements Comparable<Student> {
    private String name;
    private double gpa;

    public Student(String name, double gpa) {
        this.name = name;
        this.gpa = gpa;
    }

    // Getters와 다른 기본 메소드 생략

    @Override
    public int compareTo(Student other) {
        // GPA를 기준으로 학생들을 내림차순으로 비교합니다
        return Double.compare(other.gpa, this.gpa);
    }
}

<결과>

이 예제에서는 Comparable 인터페이스를 구현한 Student 클래스를 만들었습니다. ‘compareTo()’ 메서드는 GPA를 내림차순으로 비교하도록 재정의되었습니다. 이 메소드를 사용하여 학생 목록을 GPA를 기준으로 정렬했습니다.


Comparator로 정렬 및 출력

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Student> studentsList = new ArrayList<>();
        studentsList.add(new Student("John", 3.8));
        studentsList.add(new Student("Alice", 4.0));
        studentsList.add(new Student("Bob", 3.5));

        // 이름별로 학생 정렬(알파벳 순서)
        Comparator<Student> nameComparator = new NameComparator();
        Collections.sort(studentsList, nameComparator);

        // 정렬된 학생 목록 출력
        for (Student student : studentsList) {
            System.out.println(student.getName() + " - GPA: " + student.getGpa());
        }
    }
}

class NameComparator implements Comparator<Student> {
    @Override
    public int compare(Student student1, Student student2) {
        return student1.getName().compareTo(student2.getName());
    }
}

<결과>

이 예제에서는 Comparator 인터페이스를 구현한 NameComparator 클래스를 만들었습니다. ‘compare()’ 메서드는 이름을 알파벳순으로 비교하도록 재정의되었습니다. 이 메소드를 사용하여 학생 목록을 이름별로 정렬했습니다.


binarySearch

Collections.binarySearch() 메서드는 정렬된 List에서 이진 검색을 합니다. 찾은 경우 검색된 요소의 인덱스를 반환하고 요소가 없으면 삽입 지점을 나타내는 음수 값을 반환합니다.

binarySearch가 제대로 작동하려면 List를 정렬해야 합니다. List가 정렬되지 않으면 결과를 예측할 수 없습니다.

List<Integer> sortedNumbers = Arrays.asList(1, 3, 5, 7, 9);
int index = Collections.binarySearch(sortedNumbers, 5); // 2를 반환 (index of value 5)

indexOf() 및 lastIndexOf()

List<String> fruitsList = Arrays.asList("Apple", "Orange", "Banana", "Apple");

int firstIndex = fruitsList.indexOf("Apple"); // 0을 반환 ("Apple"의 첫 번째 인덱스)
int lastIndex = fruitsList.lastIndexOf("Apple"); // 3을 반환 ("Apple"의 마지막 인덱스)

결론

자바 List는 특정 순서로 요소들을 관리할 수 있도록 하는 Java Collections Framework에서 제공하는 데이터 구조입니다. 자바 List는 데이터를 효율적으로 저장, 조작 및 검색할 수 있습니다.

  • List 인터페이스: 중복 값을 허용하여 특정 순서로 요소를 저장할 수 있습니다.
  • ArrayList : ArrayList는 List 인터페이스의 구현체입니다. 빠른 액세스 시간을 제공하지만 배열 크기 조정으로 인해 삽입 및 삭제 속도가 느려질 수 있습니다.
  • LinkedList : LinkedList는 이중 연결 목록 데이터 구조를 사용하는 또 다른 목록 구현입니다. 특히 목록의 시작 또는 중간에서 효율적인 삽입 및 삭제를 제공하지만 액세스 시간이 느려집니다.
  • Vector : Vector는 List 인터페이스의 동기화된 구현으로 스레드로부터 안전합니다. 동시 액세스가 필요한 다중 스레드 환경에 적합합니다.
  • 정렬 : 목록은 요소 자체에 의해 정의된 자연 순서(Comparable 인터페이스를 통해) 또는 사용자 지정 정렬 기준(Comparator 인터페이스를 통해)을 사용하여 정렬할 수 있습니다.
  • 검색: 정렬된 목록에 대한 이진 검색 또는 요소 발생을 찾기 위한 indexOf() 및 lastIndexOf() 메서드를 사용하여 효율적인 검색을 수행할 수 있습니다.

자바 관련 추가 정보

  • 자바 boolean에 대해서 궁금하시다면 여기를 클릭해 주세요.
  • 자바 final에 대해서 궁금하시다면 여기를 클릭해 주세요.
  • 최신 자바 프레임 워크가 궁금하시다면 여기를 클릭해 주세요.

Leave a Comment