技術のメモ箱

Java/データ構造

リスト

List<E>

Listは不可変リスト

jshell> var numbers = List.of(2, 4, 6)
numbers ==> [2, 4, 6]

jshell> numbers.get(1)
$2 ==> 4

jshell> numbers.size()
$3 ==> 3

jshell> /v numbers
|    List<Integer> numbers = [2, 4, 6]

ArrayList<E>

ArrayListは可変リスト

jshell> var numbers2 = new ArrayList()
numbers2 ==> []

jshell> numbers2.add(3)
$2 ==> true

jshell> numbers2.add(5)
$3 ==> true

jshell> numbers2
numbers2 ==> [3, 5]

jshell> numbers2.set(1, 7)
$4 ==> 5

jshell> numbers2
numbers2 ==> [3, 7]

配列

宣言の仕方

int numbers1[] = new int[5];
int[] numbers2 = new int[5];
int numbers3[] = new int[]{1, 2, 3, 4, 5};
int numbers4[] = {1, 2, 3, 4, 5};

配列の扱い方

jshell> var scores = new int[3]
scores ==> int[3] { 0, 0, 0 }

jshell> /v scores
|    int[] scores = int[3] { 0, 0, 0 }

jshell> scores.length
$2 ==> 3

jshell> scores[1] = 85
$3 ==> 85

jshell> scores
scores ==> int[3] { 0, 85, 0 }

多次元配列

jshell> var multi = new int[2][3]
multi ==> int[2][] { int[3] { 0, 0, 0 }, int[3] { 0, 0, 0 } }

jshell> multi[1][2] = 5
$2 ==> 5

jshell> multi
multi ==> int[2][] { int[3] { 0, 0, 0 }, int[3] { 0, 0, 5 } }

jshell> var multi2 = new int[][]{{1, 2}, {3, 4, 5}}
multi2 ==> int[2][] { int[2] { 1, 2 }, int[3] { 3, 4, 5 } }

レコード

レコードはJava 16から導入された。レコードの要素をコンポーネントと言う。

jshell> record Exam(String name, String subject, int score) {}
|  次を作成しました: レコード Exam

jshell> var e1 = new Exam("kis", "math", 80)
e1 ==> Exam[name=kis, subject=math, score=80]

jshell> e1.name()
$3 ==> "kis"

マップ

Map

Mapはキーと値を結び付けるデータ構造。Mapは不変のマップ。

jshell> var fruits = Map.of("apple", "りんご", "grape", "ぶどう")
fruits ==> {grape=ぶどう, apple=りんご}

jshell> fruits.get("grape")
$5 ==> "ぶどう"

jshell> fruits.get("banana")
$6 ==> null

jshell> fruits.getOrDefault("banana",  "みつからない")
$7 ==> "みつからない"

HashMap

HashMapは可変のマップ。

jshell> var animals = new HashMap()
animals ==> {}

jshell> animals.put("cat", "ねこ")
$9 ==> null

jshell> animals.put("dog", "いぬ")
$10 ==> null

jshell> animals
animals ==> {cat=ねこ, dog=いぬ}

jshell> animals.put("cat", "猫")
$12 ==> "ねこ"

jshell> animals
animals ==> {cat=猫, dog=いぬ}
pagetop