JAVA

[JAVA] 자바에서 array, String, collection의 크기를 다루는 방법 length, length(), size()

chul542 2021. 11. 2. 10:32

- 마지막 원소에 접근하거나 크기로 루프를 돌릴 때 항상 헷갈리는 것이 length, length(), size()의 차이 이다.

 

1. length

- 배열에 있는 필드로 배열의 길이를 나타낸다.

String[] country = {"Korea", "America", "China", "Austrailia"}

System.out.println(country.length); // 4 (문자열이 아니라 문자열을 원소로 가지고 있는 배열이다)

2. length()

-문자열의 길이를 나타낸다.

String str = "Hi, My name is Galaxy." 

System.out.println(str); // 22 (공백을 포함한 문자열의 길이를 나타낸다.)

3. size()

-Collection 의 길이를 나타낸다.

ArrayList<Integer> intList = new ArrayList<Integer>();
intList.add(3).add(4).add(5);

System.out.println(intList); // 3 (3개의 원소가 add 되었다.)