본문 바로가기
카테고리 없음

[자바] 메서드의 매개변수의 수를 모를 때 varargs

by Sky Titan 2020. 9. 3.
728x90
 

Passing Information to a Method or a Constructor (The Java™ Tutorials > Learning the Java Language > Class

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See JDK Release Notes for information about new fe

docs.oracle.com

varargs '...'

  • 메서드에 넘길 파라미터의 개수가 정해지지 않았을 때 ... 으로 변수 타입 뒤에 표시해놓으면 유동적으로 파라미터를 넘겨받을 수 있다.
public class Main {


    static Integer sum (Integer... integers)
    {
        int sum = 0;

        for(int i = 0;i < integers.length;i++)
            sum += integers[i];
        return sum;
    }

    public static void main(String[] args) {

        System.out.println(sum(0, 2, 3, 5));
        /*
        integers[0] : 0
        integers[1] : 2
        integers[2] : 3
        integers[3] : 5
        */
    }
}
728x90

댓글