Algorithm

[JAVA] 컬렉션과 관련 메소드 설명 및 예제 코드

ioh'sDeveloper 2024. 6. 12. 00:01

 

ArrayListd add 메소드

  • 용어: 컬렉션 프레임워크 (Collection Framework)
  • 설명: List는 Java의 컬렉션 프레임워크 중 하나로, 요소의 순서가 유지되며 중복 요소를 허용하는 인터페이스입니다. ArrayList는 List 인터페이스를 구현한 클래스 중 하나로, 배열 기반의 동적 크기를 가진 리스트입니다.
import java.util.ArrayList;
import java.util.List;

public class ListExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Cherry");

        for (String fruit : list) {
            System.out.println(fruit);
        }
    }
}

 

리스트 메소드 (List Method) = add 메소드는 List 인터페이스의 메소드로, 리스트의 끝에 요소를 추가합니다.

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

public class AddExample {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);

        System.out.println(list); // 출력: [1, 2, 3]
    }
}

 

 

Collections.sort 메소드

  • 용어: 컬렉션 메소드 (Collection Method)
  • 설명: Collections는 유틸리티 클래스이며, sort 메소드는 List를 정렬하는 정적 메소드입니다. 기본적으로 요소의 자연 순서를 사용하거나 Comparator를 제공하여 정렬할 수 있습니다.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Banana");
        list.add("Apple");
        list.add("Cherry");

        Collections.sort(list);

        System.out.println(list); // 출력: [Apple, Banana, Cherry]
    }
}
 

Comparable 인터페이스와 compareTo 메소드

  • 용어: 인터페이스 (Interface)
  • 설명: Comparable은 Java에서 자연 순서를 정의하기 위해 사용되는 인터페이스로, compareTo 메소드를 통해 객체 간의 순서를 결정합니다.
public class Fraction implements Comparable<Fraction> {
    int numerator;
    int denominator;

    public Fraction(int numerator, int denominator) {
        this.numerator = numerator;
        this.denominator = denominator;
    }

    @Override
    public int compareTo(Fraction other) {
        return Double.compare((double) this.numerator / this.denominator,
                              (double) other.numerator / other.denominator);
    }
}

메소드 (Method) = compareTo는 Comparable 인터페이스에 정의된 메소드로, 두 객체를 비교하여 순서를 결정합니다. 음수, 0, 양수를 반환하여 각각 현재 객체가 작음, 같음, 큼을 나타냅니다.

public class Fraction implements Comparable<Fraction> {
    int numerator;
    int denominator;

    public Fraction(int numerator, int denominator) {
        this.numerator = numerator;
        this.denominator = denominator;
    }

    @Override
    public int compareTo(Fraction other) {
        double thisValue = (double) this.numerator / this.denominator;
        double otherValue = (double) other.numerator / other.denominator;
        return Double.compare(thisValue, otherValue);
    }
}

public class CompareToExample {
    public static void main(String[] args) {
        Fraction f1 = new Fraction(1, 2);
        Fraction f2 = new Fraction(1, 3);

        if (f1.compareTo(f2) > 0) {
            System.out.println("f1 is greater than f2");
        } else if (f1.compareTo(f2) < 0) {
            System.out.println("f1 is less than f2");
        } else {
            System.out.println("f1 is equal to f2");
        }
    }
}
 

PriorityQueue와 Comparator

  • 용어: 컬렉션 프레임워크 (Collection Framework) - 우선순위 큐 (Priority Queue) 
  • 용어: PriorityQueue (컬렉션 프레임워크), Comparator (비교자)
  • 개념: PriorityQueue는 요소들이 우선순위에 따라 정렬되고 큐의 앞에 높은 우선순위의 요소가 위치하는 자료 구조입니다. Comparator는 두 요소를 비교하여 정렬 순서를 정의합니다.
  • 설명: PriorityQueue는 Java의 컬렉션 프레임워크 중 하나로, 요소가 자연 순서 또는 사용자 정의 비교자(Comparator)에 따라 정렬되는 큐입니다. 위 코드에서 PriorityQueue는 람다 표현식을 사용하여 Comparator를 정의하고 있습니다. 이 Comparator는 두 분수의 값을 비교하여 우선순위를 결정합니다.
import java.util.PriorityQueue;

public class PriorityQueueExample {
    public static void main(String[] args) {
        // Comparator를 사용하여 역순으로 정렬된 우선순위 큐 생성
        PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);

        pq.offer(10);
        pq.offer(20);
        pq.offer(15);

        while (!pq.isEmpty()) {
            System.out.println(pq.poll()); // 출력: 20, 15, 10
        }
    }
}

 

offer poll 메소드

  • 용어: offer 메소드 (PriorityQueue의 메소드)
  • 설명: offer 메소드는PriorityQueue 클래스의 메소드로, 요소를 큐에 삽입합니다. 삽입에 성공하면 true를 반환하고, 큐의 용량 제한으로 인해 삽입에 실패하면 false를 반환합니다. PriorityQueue에서는 요소가 적절한 위치에 삽입되어 우선순위가 유지됩니다.
  • 개념: offer 메소드는 큐에 요소를 추가합니다. PriorityQueue의 경우, 요소는 정의된 우선순위에 따라 적절한 위치에 삽입됩니다.
import java.util.PriorityQueue;

public class OfferExample {
    public static void main(String[] args) {
        PriorityQueue<String> pq = new PriorityQueue<>();

        pq.offer("Banana");
        pq.offer("Apple");
        pq.offer("Cherry");

        while (!pq.isEmpty()) {
            System.out.println(pq.poll()); // 출력: Apple, Banana, Cherry
        }
    }
}

  • 용어: poll 메소드 (PriorityQueue의 메소드)
  • 설명: poll 메소드는 큐 인터페이스의 메소드로, 큐의 헤드를 제거하고 반환합니다. 큐가 비어있으면 null을 반환합니다. PriorityQueue에서는 가장 우선순위가 높은 요소가 제거되고 반환됩니다.
  • 개념: poll 메소드는 큐의 헤드를 제거하고 반환합니다. PriorityQueue의 경우, 가장 높은 우선순위를 가진 요소가 제거됩니다.
import java.util.PriorityQueue;

public class PollExample {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();

        pq.offer(10);
        pq.offer(20);
        pq.offer(15);

        System.out.println(pq.poll()); // 출력: 10
        System.out.println(pq.poll()); // 출력: 15
        System.out.println(pq.poll()); // 출력: 20
    }
}