When getting the length of an array or a character string in Java, it gets confused as to whether it is length, length () or size (), so I summarized that area for study.
length | length() | size() |
---|---|---|
ArrayLength of | StringLength of | collectionNumber of elements of |
length
length is used to get the length of the array.
int[] a = new int [100];
a.length; // 100
a.length(); //Compile error
Since the length field, which is a member of the array, is used, () is unnecessary.
length() length () is used to get the length of a string.
String str = "aiueo"
str.length; //Compile error
str.length(); // 5
() Is required because the length method is used to get the length of the character string. Even in the case of full-width characters, it counts the number of characters correctly (humanly).
String zenkaku = "AIUEO"
zenkaku.length(); // 5
size()
You can get the number of elements in a collection (List, Set, etc.) with size ().
ArrayList<Integer> b = new ArrayList<>();
for(int i = 0; i < 100; i++){
b.add(i);
}
b.size() //100
size () seems to be a method defined in the Collection class. So you can use size () for all collections.
http://www.kab-studio.biz/Programing/JavaA2Z/Word/00000290.html
Recommended Posts