Where is array's length property defined?

前端 未结 7 902
悲哀的现实
悲哀的现实 2020-11-22 13:41

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

ArrayList arr = new ArrayL         


        
7条回答
  •  一向
    一向 (楼主)
    2020-11-22 14:20

    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 intsList = new ArrayList();
    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
    

提交回复
热议问题