I about me

[Final] collections 본문

Java

[Final] collections

ssungni 2024. 6. 15. 22:51

# slide 19 정리

import java.util.*;

public class CollectionsExample {
    public static void main(String[] args) {
    	List<Integer> list = new ArrayList<>(Arrays.asList(5, 3, 8, 1, 9));
        
        // sort: Sorts the elements of a List.
        Collections.sort(list);
        System.out.println(list); // [1, 3, 5, 8, 9]
        
        // binarySearch: Locates an object in a List, using the high-performance binary search algorithm
        int index1 = Collections.binarySearch(list, 5);
        System.out.println(index1);  // 2
        
        // reverse(뒤집기): Reverses the elements of a List
        Collections.reverse(list);
        System.out.println(list); // [9, 8, 5, 3, 1]
        
        // shuffle(섞기): Randomly orders a List's elements.
        Collections.shuffle(list);
        System.out.println(list); // [3, 9, 1, 5, 8]
        
        // fill(모든 원소를 바꾸고 싶을 때 유용): Sets every List element to refer to a specified object.
        Collections.fill(list, 0);
        System.out.println(list); // [0, 0, 0, 0, 0]
        
        // copy (B <- A, 즉 B의 배열의 크기는 A보다 커야함): Copies references from one List into another.
        List<Integer> src = new ArrayList<>(Arrays.asList(1, 2, 3));
        List<Integer> dest = new ArrayList<>(Arrays.asList(4, 5, 6, 7, 8));
        Collections.copy(dest, src);
        System.out.println(dest); // [1, 2, 3, 7, 8]
        
       // addAll: Appends all elements in an array to a Collection.
        List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));
        Collections.addAll(list, 4, 5, 6);
        System.out.println(list); // [1, 2, 3, 4, 5, 6]
        
        // frequency (특정 요소가 몇 번 나타나는지 계산): Calculates how many collection elements are equal to the specified element.
        List<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "apple", "orange", "apple"));
        int freq = Collections.frequency(list, "apple");
        System.out.println("Frequency of 'apple': " + freq); // 3
        
        // disjoint (공통 요소가 없으면 true, 있으면 false를 반환): Determines whether two collections have no elements in common.
        List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3));
        List<Integer> list2 = new ArrayList<>(Arrays.asList(4, 5, 6));
        List<Integer> list3 = new ArrayList<>(Arrays.asList(3, 4, 5));
        
        boolean result1 = Collections.disjoint(list1, list2);
        System.out.println("List1 and List2 disjoint: " + result1); // true
        
        boolean result2 = Collections.disjoint(list1, list3);
        System.out.println("List1 and List3 disjoint: " + result2); // false
 }

 

'Java' 카테고리의 다른 글

[Final] Serialization  (1) 2024.06.14
[Final] File I/O  (0) 2024.06.13
[Final] Exception Handling 문제 풀이  (0) 2024.06.11
[Final] Exception  (0) 2024.06.11
[Final] Interface  (0) 2024.06.10