언어(Language)/Java

[Java] length, length(), size() 차이점

다문다뭉 2024. 9. 27. 22:59

length

length는 배열의 길이를 구할 때 사용된다.

최초 배열이 생성될 때 길이가 결정되는 상수 값이다.

arrays(int[], double[], String[])

public class lenTest {
    public static void main(String[] args) {
        String[] arr = {"a", "b", "c"}; // 배열
        String[] arrTmp = new String[7]; // 빈 배열

        // length : 배열의 길이
        arr.length // 3
        arrTmp.length // 7 (배열에 저장된 원소 수가 아님)
    }
}

length()

length()는 문자열의 길이를 구할 때 사용된다.

유니코드 코드 단위의 개수이기 때문에, 영문과 한글 항상 1개로 간주한다.

String related Object(String, StringBuilder etc)

    /**
     * Returns the length of this string.
     * The length is equal to the number of <a href="Character.html#unicode">Unicode
     * code units</a> in the string.
     *
     * @return  the length of the sequence of characters represented by this
     *          object.
     */
    public int length() {
        return value.length >> coder();
    }
public class lenTest {
    public static void main(String[] args) {
        String[] arr = {"a", "b", "c"}; // 배열
        String[] arrTmp = new String[7]; // 빈 배열
        String str = "abcde"; // 문자열

        // length() : 문자열의 길이
        str.length() // 5

        // 배열 원소의 길이
        arr[0].length() // 1
    }
}

size()

size()는 컬렉션 프레임워크 타입의 길이를 구할 때 사용된다.

Collection Object(ArrayList, Set etc)

import java.util.ArrayList;
public class lenTest {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>(); // 리스트
        list.add("a");

        // size() : 컬렉션 프레임워크 타입의 길이
        list.size() // 1
    }
}