問題一覧に戻る
中級コレクション
問題87: Collectionsユーティリティ
Collectionsクラスは一般的なコレクション操作のための静的ユーティリティメソッドを提供します。sort()、reverse()、shuffle()などのメソッドはコレクションを直接変更し、unmodifiableList()は読み取り専用ビューを作成します。これらのユーティリティは任意のList実装で動作し、カスタムコードを書くことなくソート、検索、変換のための効率的なアルゴリズムを提供します。
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(3);
numbers.add(1);
numbers.add(4);
// リストをソート
Collections.__(numbers);
System.out.println("Sorted: " + numbers);
// リストを逆順に
Collections.__(numbers);
System.out.println("Reversed: " + numbers);
// 不変リスト
List<String> readOnly = Collections.__(
Arrays.asList("A", "B")
);
}
}