0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Java ArrayListクラス 使い方

Posted at

はじめに

学習用のメモになります。

#ArrayListとは?
ArrayListは複数の要素を入れるための入れ物ようなもの

#ArrayListと配列の違い

  • 配列には格納できる要素の大きさが決まっています。その為、あらかじめ決めた大きさを超える要素を格納すると、IndexOutOfBoundsExceptionエラーが発生します。
  • ArrayListは要素数の大きさが決まっていません。要素数の上限値を気にせず、どんどん値を追加できます。

#ArrayListを使う

import java.util.*;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> team = new ArrayList<String>();

        team.add("勇者");
        team.add("魔法使い");
        for (String member : team) {
            System.out.println(member);
        }
    }
}

##ArrayListを作成

import java.util.*;

ArrayList<String> team = new ArrayList<String>();

##ArrayListの要素を追加

team.add("勇者");
team.add("魔法使い");

addで要素を追加

##ArrayListの要素をループする

for (String member : team) {
    System.out.println(member);
}

##ArrayListの要素を出力

System.out.println(team.get(0));

getで要素を出力

##ArrayListのサイズを出力

System.out.println(team.size());

sizeで要素の長さを出力

##ArrayListの要素の更新

team.set(1, "忍者");

setで追加

##ArrayListの要素の削除

team.remove(1);

removeで削除

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?