4

Why is the number of elements in a list referred to as "size", while the length of an array referred to as "length"?

package com.mycompany.javatest;

import java.util.*;

public class JavaTest {

    public static void main(String[] args) {

        List<String> stringList = new ArrayList<String>();
        stringList.add("one");
        stringList.add("two");
        stringList.add("three");
        System.out.println("Size of list is: " + stringList.size());

        String[] stringArray = {"one", "two", "three"};
        System.out.println("Length of array is: " + stringArray.length);
    }
}
birgersp
  • 3,909
  • 8
  • 39
  • 79
  • Not to mix them? I don't believe you can get a real answer except from an architect of Oracle – Nicolas Filotto Dec 02 '16 at 11:42
  • First thing comes to my mind, that's the way these classes are designed and I don't find a reason to question on that. – Mritunjay Dec 02 '16 at 11:42
  • 1
    ArrayList creates a mutable object. So to know its current capacity, size() is a suitable method. Whereas String creates a immutable object whose capacity is fixed and thus length() is used as a suitable method. – kiner_shah Dec 02 '16 at 11:46
  • 1
    @kiner_shah Why would length() not be suited for a mutable object?... And the other way around? – Seth Dec 02 '16 at 11:48
  • for an ArrayList, the variable that they use to store the size of the list is called "size", it is declared as "**private int size;**", that might be the reason they named the method after the name of the variable. I'm not sure about the array though. – Adit A. Pillai Dec 02 '16 at 11:49
  • @Seth, Honestly, I have no idea why other way round is not possible. I just gave an appropriate possibility of why the different names are used. – kiner_shah Dec 02 '16 at 11:51
  • 1
    Possible duplicate of [Difference between size and length methods?](http://stackoverflow.com/questions/20192843/difference-between-size-and-length-methods) – Michael Dec 02 '16 at 11:51
  • for detailed information you can refer to the [JLS](http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.7) – Adit A. Pillai Dec 02 '16 at 11:53

1 Answers1

5

Take a look at the definition of both words from Oxford Dictionaries:

Size: The relative extent of something; a thing's overall dimensions or magnitude; how big something is: ‘the schools varied in size’ ‘a forest the size of Wales’

Length: The measurement or extent of something from END TO END; the greater of two or the greatest of three dimensions of an object: ‘the delta is twenty kilometres in length’

Even if both can be understood as "extent of something", they differ in terms of measurement. Length measures the END to END of something, that's very appropriated to an Array. Size measures the size of a List, how big is the List?

The fact that Lists are dynamic (it can grow) and Arrays are Not helps you to visualize why length for Array and why size for List.

Greetings