Help us understand the problem. What is going on with this article?

JAVA size()メソッドの注意点 ArrayList

More than 3 years have passed since last update.

■SizeMethod 例①

import java.util.ArrayList;

public class SizeMethod {
    public static void main(String[] args) {
        // AutoBoxingによりラッパークラスCharacterがプリミティブ型charに自動変換される
        ArrayList<Character> moji = new ArrayList<Character>();
        moji.add('A');
        moji.add('B');
        moji.add('C');
        System.out.println(moji.size());

    }

}

■SizeMethod 例①実行結果
3

■SizeMethod 例②

import java.util.ArrayList;

public class SizeMethod {
    public static void main(String[] args) {
        // AutoBoxingによりラッパークラスCharacterがプリミティブ型charに自動変換される
        ArrayList<Character> moji = new ArrayList<Character>();
        moji.add('A');
        moji.add('B');
        moji.add('C');
        moji.add(0, 'D');
        System.out.println(moji.size());

    }

}

■SizeMethod 例②実行結果
4

■SizeMethod 例③

import java.util.ArrayList;

public class SizeMethod {
    public static void main(String[] args) {
        // AutoBoxingによりラッパークラスCharacterがプリミティブ型charに自動変換される
        ArrayList<Character> moji = new ArrayList<Character>();
        moji.add('A');
        moji.add('B');
        moji.add('C');
        moji.remove(0);
        System.out.println(moji.size());

    }

}

■SizeMethod 例②実行結果
2

addは追加 setは上書き

■SizeMethod 例③実行結果

import java.util.ArrayList;

public class SizeMethod {
    public static void main(String[] args) {
        // AutoBoxingによりラッパークラスCharacterがプリミティブ型charに自動変換される
        ArrayList<Character> moji = new ArrayList<Character>();
        moji.add('A');
        moji.add('B');
        moji.add('C');
        moji.add(0, 'D');
        System.out.println(moji.size());
        System.out.println(moji);
        System.out.println(moji.get(3));
        moji.set(2, 'E');
        System.out.println(moji.size());

    }

}

■SizeMethod 例③実行結果
4
[D, A, B, C]
C
4

icelandnono
24歳です 職場は渋谷です 渋谷興味ない。。 新橋とかで働きたい。。銀座がすき
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした