LoginSignup
9
12

More than 5 years have passed since last update.

Javaでオブジェクトの集合を扱う

Posted at

Javaにはリストやセット、マップなどのオブジェクトの集合を扱う仕組みがあります。
それぞれの特徴と使用例は以下のようになります。

ArrayList (リスト)

ArrayListは一般的な配列を表します。

ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");

String x = list.get(1);
System.out.println("Bを出力:" + x);

for (int i = 0; i < list.size(); i++) {
    // A, B, C
    System.out.println(list.get(i));
}

if (list.contains("A")) {
    System.out.println("値にAが含まれていれば呼び出される");
}

// 全ての要素を削除する
list.clear();

LinkedListもArrayListと同じように使うことができます。LinkedListは挿入や削除を頻繁に行う場合はArrayListよりも高速です。しかし、get()を使う場合はArrayListの方が高速です。

HashSet (セット)

HashSetは要素の重複が許されない、順序の保証がない配列を表します。

HashSet<String> set = new HashSet<String>();
set.add("A");
set.add("B");
set.add("C");

Iterator it = set.iterator();
while (it.hasNext()) {
    // A, B, C 順不同
    System.out.println(it.next());
}

if (set.contains("A")) {
    System.out.println("値にAが含まれていれば呼び出される");
}

// 全ての要素を削除する
set.clear();

TreeSetもHashSetと同じように使うことができます。TreeSetは要素が自動的にソートされるのが特徴です。

注意点

大量のデータを扱う時はArrayListよりHashSetの方が処理を高速に行えます。

HashMap (マップ)

HashMapはキーと値の組み合わせの連想配列を表します。

HashMap<String, String> map = new HashMap<String, String>();
map.put("AL1", "A");
map.put("AL2", "B");
map.put("AL3", "C");

String x = map.get("AL1");
System.out.println("Aを出力:" + x);

Iterator it = map.keySet().iterator();
while(it.hasNext()) {
    String key = (String)it.next();
    // AL1:A, AL2:B, AL3:C 順不同
    System.out.println(key + ":" + map.get(key));
}

if (map.containsKey("AL1") || map.containsValue("A")) {
    System.out.println("キーにAL1か値にAが含まれていれば呼び出される");
}

// 全ての要素を削除する
map.clear();

TreeMapもHashMapと同じように使うことができます。TreeMapは要素がキーによって自動的にソートされるのが特徴です。

9
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
12