About the difference between length, length(), size() in Java

I used to think that I could do it, but one day I was suddenly in a trance when faced with this written test question, and there was a high chance of confusion and wrong answers. I wonder if there are other people like me.

So I wrote this question down today, hoping to be more impressed.


First distinguish between length and length();

length is not a method, it is an attribute, an attribute of an array;

public static void main(String[] args) {
	int[] intArray = {1,2,3};
	System.out.println("The length of this array is: " + intArray.length);
}


length() is a method of String;

public static void main(String[] args) {
	String str = "HelloWorld";
	System.out.println("The length of this string is: " + str.length());
}

Enter the length() method to see the implementation

private final char value[];

public int length() {
        return value.length;
    }

The explanation in the comments is

@return     the length of the sequence of characters represented by this object.

That is, the length of the character sequence represented by the object, so in the final analysis, the bottom attribute of length is the last thing to look for;


The size() method is a method of the List collection;

public static void main(String[] args) {
	List<String> list = new ArrayList<String>();
	list.add("a");
	list.add("b");
	list.add("c");
	System.out.println("The length of this list is: " + list.size());
}

In the method of List, there is no length() method;

Also look at the source code of an ArrayList

private final E[] a;

ArrayList(E[] array) {
       if (array==null)
             throw new NullPointerException();
       a = array;
}

public int size() {
       return a.length;
}

It can be seen from this paragraph that the underlying implementation of list is actually an array, and the last thing the size() method is looking for is actually the length attribute of the array;

In addition, in addition to List, Set and Map also have size() method, so to be precise, size() method is for sets.


Summarize:

length - property of the array;

length()——Method of String;

size() - method of collection;

Remember.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325475556&siteId=291194637