概要
ArrayListはOracleの公式ページでも明記しているクラスです。
Java SE 11 Programmer I (1Z0-815-JPN) 試験
インタフェースの作成と実装
具象クラスの継承とインタフェース、抽象クラスの継承
ListインタフェースとArrayListクラスの使用
ラムダ式の理解
業務でもよく使用するため、しっかりと押さえて置きましょう。
特徴
・オブジェクト型であればどのような方でも扱うことが可能
・増やした要素は追加した順に並ぶ
・null値も値として扱うことが可能
・重複した値の保持が可能
・スレッドセーフではない
メソッド
基本的かつよく使うメソッドです。
add
要素を追加します。
追加する方法には、要素だけを指定する場合と、要素とindexを指定する方法があります。
要素だけ指定する
1 2 3 4 5 6 |
// add(E e) List<String> strings = new ArrayList<>(); strings.add(null); strings.add("A"); strings.add("B"); System.out.println(strings); |
実行結果
1 |
[null, A, B] |
要素とindexを指定する
1 2 3 4 5 6 |
//add(int index, E e) List<String> strings = new ArrayList<>(); strings.add(0,null); strings.add(1, "A"); strings.add(2, "B"); System.out.println(strings); |
実行結果
1 |
[null, A, B] |
indexを指定する場合、最も小さいindex番号を指定する必要があります。
もし、要素が1つもないのであれば指定可能な最小のindex番号は「0」です。
そこに「1」を指定すると、IndexOutOfBoundsExceptionがスローされます。
1 2 3 4 |
//add(int index, E e) List<String> exception = new ArrayList<>(); exception.add(1,null); System.out.println(exception); |
実行結果
1 |
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0 |
set
すでにある要素を上書きします。
1 2 3 4 5 6 7 |
// set(int index, E e) List<String> strings = new ArrayList<>(); strings.add(null); System.out.println(strings); strings.set(0, "A"); System.out.println(strings); |
実行結果
index=0のnullが、Aに上書きされています。
1 2 |
[null] [A] |
get
指定したインデックスの要素を取得します。
1 2 3 4 5 6 7 8 9 |
// get(E e) List<String> strings = new ArrayList<>(); strings.add(null); strings.add("A"); strings.add("B"); System.out.println(strings.get(0)); System.out.println(strings.get(1)); System.out.println(strings.get(2)); |
実行結果
1 2 3 |
null A B |
存在しないインデックスを指定した場合は、IndexOutOfBoundsExceptionがthrowされる
1 2 3 4 5 6 7 |
// 存在しないインデックスを指定した場合は、IndexOutOfBoundsExceptionがthrowされる System.out.println(strings.get(3)); Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248) |
remove
要素を削除します。
要素を指定する方法と、indexを指定する方法があります。
要素を指定する
1 2 3 4 5 6 7 |
// remove(E e) List<String> strings = new ArrayList<>(); strings.add(null); strings.add("A"); strings.add("B"); strings.remove("A"); // 要素を指定 System.out.println(strings); |
実行結果
1 |
[null, B] |
indexを指定する
1 2 3 4 5 6 7 |
// remove(int index) List<String> strings = new ArrayList<>(); strings.add(null); strings.add("A"); strings.add("B"); strings.remove(1); // indexを指定 System.out.println(strings); |
実行結果
1 |
[null, B] |
まとめ
- ArrayListは業務でも良く使うし、JavaSilverの試験にも出題される。
- オブジェクト型であればどのような方でも扱うことが可能であるという特徴がある。
- 代表的なメソッドは、add(追加)、set(上書き)、get(取得)、remove(削除)である。
コメント