LoginSignup
11
12

More than 5 years have passed since last update.

String.length() と 配列.length が違う理由(解決してない)

Last updated at Posted at 2014-05-09
String str = "a";
int[] array = new int[10];
System.out.println(
        "文字列の長さ = " + str.length()
         + "配列の要素数 = " + array.length);

なぜ、配列のlength には() がつかないのか?
疑問に思ってAPI のソース(1.8)を見てみました。

String.java#length()

    /**
     * Returns the length of this string.
     * The length is equal to the number of <a href="Character.html#unicode">Unicode
     * code units</a> in the string.
     *
     * @return  the length of the sequence of characters represented by this
     *          object.
     */
    public int length() {
        return value.length;
    }

なるほど、こっちはメソッドになっています。
value は、charの配列ですね。

    /** The value is used for character storage. */
    private final char value[];

配列のlength

一般的には配列オブジェクトのフィールド変数と説明されるやつですね。
が、あれ、クラスはどれみればいいんだ?
java.lang.reflect.Array にもそんなフィールドはないし。
java.lang.Class の中にこんなのがあったけど

2699     static class MethodArray {
2700         private Method[] methods;
2701         private int length;

MethodArray?
どなたか識者のかたお助けを..

11
12
6

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
11
12