Where is array's length property defined?

2018-12-31 16:12发布

We can determine the length of an ArrayList<E> using its public method size(), like

ArrayList<Integer> arr = new ArrayList(10);
int size = arr.size();

Similarly we can determine the length of an Array object using the length property

String[] str = new String[10];
int size =  str.length;

Whereas the size() method of ArrayList is defined inside the ArrayList class, where is this length property of Array defined?

标签: java arrays
7条回答
闭嘴吧你
2楼-- · 2018-12-31 17:10

Even though this is not a direct answer to the question, it is an addition to the .length vs .size() argument. I was researching something related to this question so when I came across it I noticed that the definition(s) provided here

The public final field length, which contains the number of components of the array.

is not "exactly" correct.

The field length contains the number of available places to put a component, not the number of components present in the array. So it represents the total available memory allocated to that array, not how much of that memory is filled.

Array Memory Allocation

Example:

static class StuffClass {
    int stuff;
    StuffClass(int stuff) {
        this.stuff = stuff;
    }
}

public static void main(String[] args) {

    int[] test = new int[5];
    test[0] = 2;
    test[1] = 33;
    System.out.println("Length of int[]:\t" + test.length);

    String[] test2 = new String[5];
    test2[0] = "2";
    test2[1] = "33";    
    System.out.println("Length of String[]:\t" + test2.length);

    StuffClass[] test3 = new StuffClass[5];
    test3[0] = new StuffClass(2);
    test3[1] = new StuffClass(33);
    System.out.println("Length of StuffClass[]:\t" + test3.length);         
}

Output:

Length of int[]:        5
Length of String[]:     5
Length of StuffClass[]: 5

However, the .size() property of the ArrayList does give the number of elements in the list:

ArrayList<Integer> intsList = new ArrayList<Integer>();
System.out.println("List size:\t" + intsList.size());
intsList.add(2);
System.out.println("List size:\t" + intsList.size());
intsList.add(33);
System.out.println("List size:\t" + intsList.size());

Output:

List size:  0
List size:  1
List size:  2
查看更多
登录 后发表回答