LoginSignup
7
3

More than 3 years have passed since last update.

【Java】Listの要素を削除する

Posted at

要素を一つ削除する

◆要素の値を指定する場合

    public static void main(String[] args) {

        String arr[] = {"orange","apple","cherry","melon","grape"};

        List<String> list = new ArrayList<>(Arrays.asList(arr));
        list.remove("apple");
    }

◆要素のINDEX番号を指定する場合

    public static void main(String[] args) {

        String arr[] = {"orange","apple","cherry","melon","grape"};

        List<String> list = new ArrayList<>(Arrays.asList(arr));
        list.remove(1);
    }

要素を複数削除する

削除したい要素を持つlistを生成し、list.removeAll()メソッドの引数に入れる

    public static void main(String[] args) {

        String arr[] = {"orange","apple","cherry","melon","grape"};

        List<String> list = new ArrayList<>(Arrays.asList(arr));

        List<String> remove = new ArrayList<>();
        Collections.addAll(remove,"apple","melon");

        list.removeAll(remove);

        System.out.println(list);
    }

要素をすべて削除する

全削除なのでlist.sizeは0になる

    public static void main(String[] args) {

        String arr[] = {"orange","apple","cherry","melon","grape"};

        List<String> list = new ArrayList<>(Arrays.asList(arr));

        list.clear();

        System.out.println(list.size());
    }
7
3
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
7
3