티스토리 뷰

BackEnd/Java

가변 인자 (varargs)

철철22 2018. 11. 13. 10:07
반응형

혹시 JAVA를 사용하면서 String.format()을 사용해 본적이 있나요?


보통 이런식으로 사용하잖아요???


System.out.println(String.format("%s %s", "asdf" , "fdas");


이 예시를 왜 들었냐면 JavaDoc 의 format 설명을 보면 다음과 같습니다.


 public static String format(Locale l,String format, Object... args)

Returns a formatted string using the specified locale, format string, and arguments.

 Parameters:

l - The locale to apply during formatting. If l is null then no localization is applied.
format - A format string
args - Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by The Java™ Virtual Machine Specification. The behaviour on a null argument depends on the conversion.
Returns:
A formatted string
Throws:
IllegalFormatException - If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions. For specification of all possible formatting errors, see the Details section of the formatter class specification
Since:
1.5
See Also:
Formatter


그리고 Object... args 보이시나요?


이게 가변인자 (Varargs, Variable Arguments)의 사용입니다.

필요에 인자를 가변적으로 조정할 수 있는 기술이며, jdk1.5 부터 지원하게 됩니다.


사용법은 타입... 파라미터명 이런식으로 사용하면 되요.



가변인자를 사용하게 되면 컴파일러가 배열 형태로 바꿔줍니다.


□ 가변인수에서 컴파일러가 해주는 일
◇ 매개변수를 배열로 변환해준다.
― 원본 : public static void display(String... strs)
― 컴파일러 변환 후 : public static void display(String as[])
◇ 메서드 호출 시 인자들을 이용해서 배열로 만들어 준다.
―  원본 : VarArgsMain.display("Hello", "World", "Korea");
―  컴파일러 변환 후 : VarArgsMain.display(new String[] {"Hello", "World", "Korea" });

출처: http://gyrfalcon.tistory.com/entry/Java-Varargs [Minsub's Blog]




가변인자를 사용 할 때 주의해야할 것이 있습니다.

1. 가변인자는 여러개 있어야 하며, 파라미터 마지막에 있어야 한다.


2. 가변인자를 사용할 때 인자를 넣지 않아도 정상적으로 실행이 된다. 하지만 예외처리나 방어 코드를 작성해야 한다.




참조 : 

https://opentutorials.org/module/1226/8022 

 

http://ktko.tistory.com/entry/%EC%9E%90%EB%B0%94-%EA%B0%80%EB%B3%80%EC%9D%B8%EC%9E%90Varargs%EC%97%90-%EB%8C%80%ED%95%B4%EC%84%9C


https://opentutorials.org/module/1226/8022


반응형

'BackEnd > Java' 카테고리의 다른 글

spring boot HikariCP  (1) 2019.01.06
openjdk 설치하기  (0) 2018.12.16
JAVA 디자인 패턴 강좌  (0) 2018.11.06
JAVA Singleton Pattert 싱글톤 패턴  (0) 2018.10.31
Apache Mina (아파치 미나)  (0) 2018.10.31
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함