配列
配列の宣言と初期化
// 宣言と初期化
int[] numbers = new int[5]; // 要素数5の配列
numbers[0] = 10;
numbers[1] = 20;
// 初期値付き
int[] values = {1, 2, 3, 4, 5};
// 宣言と初期化を分離
int[] arr;
arr = new int[]{1, 2, 3};
// 配列の長さ
System.out.println(values.length); // 5
配列の操作
int[] numbers = {1, 2, 3, 4, 5};
// 要素へのアクセス
System.out.println(numbers[0]); // 1
System.out.println(numbers[4]); // 5
// 要素の変更
numbers[2] = 30;
// ループで走査
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
// 拡張for文
for (int num : numbers) {
System.out.println(num);
}
多次元配列
// 2次元配列
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(matrix[1][2]); // 6
// 走査
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
// 拡張for文
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
Arrays クラス
import java.util.Arrays;
int[] numbers = {3, 1, 4, 1, 5, 9, 2, 6};
// ソート
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
// [1, 1, 2, 3, 4, 5, 6, 9]
// 検索(ソート済み配列で使用)
int index = Arrays.binarySearch(numbers, 4);
System.out.println(index); // 4
// 配列のコピー
int[] copy = Arrays.copyOf(numbers, numbers.length);
int[] partial = Arrays.copyOfRange(numbers, 0, 3);
// 比較
boolean equal = Arrays.equals(numbers, copy);
// 埋める
int[] filled = new int[5];
Arrays.fill(filled, 10); // [10, 10, 10, 10, 10]
ArrayList
可変長のリストです。
import java.util.ArrayList;
import java.util.List;
// 宣言
List<String> fruits = new ArrayList<>();
// 追加
fruits.add("apple");
fruits.add("banana");
fruits.add("orange");
// インデックス指定で追加
fruits.add(1, "grape");
// 取得
String first = fruits.get(0); // "apple"
// 更新
fruits.set(0, "melon");
// 削除
fruits.remove("banana"); // 値で削除
fruits.remove(0); // インデックスで削除
// サイズ
int size = fruits.size();
// 検索
boolean hasApple = fruits.contains("apple");
int index = fruits.indexOf("orange");
// 空かどうか
boolean isEmpty = fruits.isEmpty();
// クリア
fruits.clear();
ArrayList の走査
List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("banana");
fruits.add("orange");
// 拡張for文
for (String fruit : fruits) {
System.out.println(fruit);
}
// forEach
fruits.forEach(fruit -> System.out.println(fruit));
// イテレータ
Iterator<String> it = fruits.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
HashMap
キーと値のペアを格納するマップです。
import java.util.HashMap;
import java.util.Map;
Map<String, Integer> scores = new HashMap<>();
// 追加
scores.put("太郎", 85);
scores.put("花子", 92);
scores.put("次郎", 78);
// 取得
int taroScore = scores.get("太郎"); // 85
int unknownScore = scores.getOrDefault("不明", 0); // 0
// 更新
scores.put("太郎", 90);
// 削除
scores.remove("次郎");
// 存在確認
boolean hasTaro = scores.containsKey("太郎");
boolean has100 = scores.containsValue(100);
// サイズ
int size = scores.size();
HashMap の走査
Map<String, Integer> scores = new HashMap<>();
scores.put("太郎", 85);
scores.put("花子", 92);
// キーのみ
for (String key : scores.keySet()) {
System.out.println(key);
}
// 値のみ
for (int value : scores.values()) {
System.out.println(value);
}
// キーと値
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// forEach
scores.forEach((key, value) -> {
System.out.println(key + ": " + value);
});
HashSet
重複のない要素の集合です。
import java.util.HashSet;
import java.util.Set;
Set<String> colors = new HashSet<>();
// 追加
colors.add("red");
colors.add("green");
colors.add("blue");
colors.add("red"); // 重複は無視
System.out.println(colors.size()); // 3
// 削除
colors.remove("green");
// 存在確認
boolean hasRed = colors.contains("red");
// 走査
for (String color : colors) {
System.out.println(color);
}
集合演算
Set<Integer> setA = new HashSet<>(Arrays.asList(1, 2, 3, 4));
Set<Integer> setB = new HashSet<>(Arrays.asList(3, 4, 5, 6));
// 和集合
Set<Integer> union = new HashSet<>(setA);
union.addAll(setB); // {1, 2, 3, 4, 5, 6}
// 積集合
Set<Integer> intersection = new HashSet<>(setA);
intersection.retainAll(setB); // {3, 4}
// 差集合
Set<Integer> difference = new HashSet<>(setA);
difference.removeAll(setB); // {1, 2}
LinkedList
両端への追加・削除が高速なリストです。
import java.util.LinkedList;
LinkedList<String> list = new LinkedList<>();
// 末尾に追加
list.add("a");
list.addLast("b");
// 先頭に追加
list.addFirst("z");
// 先頭・末尾の取得
String first = list.getFirst();
String last = list.getLast();
// 先頭・末尾の削除
list.removeFirst();
list.removeLast();
不変コレクション(Java 9以降)
// 不変リスト
List<String> immutableList = List.of("a", "b", "c");
// immutableList.add("d"); // UnsupportedOperationException
// 不変セット
Set<Integer> immutableSet = Set.of(1, 2, 3);
// 不変マップ
Map<String, Integer> immutableMap = Map.of(
"one", 1,
"two", 2,
"three", 3
);
実践例:単語カウント
import java.util.*;
public class WordCounter {
public static Map<String, Integer> countWords(String text) {
Map<String, Integer> wordCount = new HashMap<>();
String[] words = text.toLowerCase().split("\\s+");
for (String word : words) {
wordCount.merge(word, 1, Integer::sum);
}
return wordCount;
}
public static void main(String[] args) {
String text = "Java is great Java is fun";
Map<String, Integer> counts = countWords(text);
counts.forEach((word, count) -> {
System.out.println(word + ": " + count);
});
}
}
まとめ
- 配列は固定長、
Arraysクラスでユーティリティ操作 ArrayListは可変長リスト、インデックスアクセスが高速LinkedListは先頭・末尾の操作が高速HashMapはキーと値のペア、検索が高速HashSetは重複なし、存在確認が高速- Java 9以降は
List.of()などで不変コレクション
次回はクラスについて詳しく学びます。