가변 개수의 인수를 허용하는 Java 메서드를 만드는 방법은 무엇입니까?
예를 들어, Java 자체 String.format()
는 가변 개수의 인수를 지원합니다.
String.format("Hello %s! ABC %d!", "World", 123);
//=> Hello World! ABC 123!
가변 개수의 인수를 받아들이는 내 함수를 어떻게 만들 수 있습니까?
후속 질문 :
나는 이것을 위해 편리한 지름길을 정말로 만들려고 노력하고 있습니다.
System.out.println( String.format("...", a, b, c) );
그래서 나는 이것을 다음과 같이 덜 장황한 것으로 부를 수 있습니다.
print("...", a, b, c);
이것을 어떻게 달성 할 수 있습니까?
편리한 방법을 작성할 수 있습니다.
public PrintStream print(String format, Object... arguments) {
return System.out.format(format, arguments);
}
그러나 보시다시피 이름이 변경되었습니다 format
(또는 printf
).
사용 방법은 다음과 같습니다.
private void printScores(Player... players) {
for (int i = 0; i < players.length; ++i) {
Player player = players[i];
String name = player.getName();
int score = player.getScore();
// Print name and score followed by a newline
System.out.format("%s: %d%n", name, score);
}
}
// Print a single player, 3 players, and all players
printScores(player1);
System.out.println();
printScores(player2, player3, player4);
System.out.println();
printScores(playersArray);
// Output
Abe: 11
Bob: 22
Cal: 33
Dan: 44
Abe: 11
Bob: 22
Cal: 33
Dan: 44
System.out.printf
동일한 방식으로 작동 하는 유사한 메서드 도 있지만 구현을 살펴보면를 printf
호출하기 만하면 format
되므로 format
직접 사용 하는 것이 좋습니다.
- Varargs
PrintStream#format(String format, Object... args)
PrintStream#printf(String format, Object... args)
This is known as varargs see the link here for more details
In past java releases, a method that took an arbitrary number of values required you to create an array and put the values into the array prior to invoking the method. For example, here is how one used the MessageFormat class to format a message:
Object[] arguments = {
new Integer(7),
new Date(),
"a disturbance in the Force"
};
String result = MessageFormat.format(
"At {1,time} on {1,date}, there was {2} on planet "
+ "{0,number,integer}.", arguments);
It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process. Furthermore, it is upward compatible with preexisting APIs. So, for example, the MessageFormat.format method now has this declaration:
public static String format(String pattern,
Object... arguments);
Take a look at the Java guide on varargs.
You can create a method as shown below. Simply call System.out.printf
instead of System.out.println(String.format(...
.
public static void print(String format, Object... args) {
System.out.printf(format, args);
}
Alternatively, you can just use a static import if you want to type as little as possible. Then you don't have to create your own method:
import static java.lang.System.out;
out.printf("Numer of apples: %d", 10);
This is just an extension to above provided answers.
- There can be only one variable argument in the method.
- Variable argument (varargs) must be the last argument.
Clearly explained here and rules to follow to use Variable Argument.
The following will create a variable length set of arguments of the type of string:
print(String arg1, String... arg2)
You can then refer to arg2
as an array of Strings. This is a new feature in Java 5.
The variable arguments must be the last of the parameters specified in your function declaration. If you try to specify another parameter after the variable arguments, the compiler will complain since there is no way to determine how many of the parameters actually belong to the variable argument.
void print(final String format, final String... arguments) {
System.out.format( format, arguments );
}
You can pass all similar type values in the function while calling it. In the function definition put a array so that all the passed values can be collected in that array. e.g. .
static void demo (String ... stringArray) {
your code goes here where read the array stringArray
}
'Program Tip' 카테고리의 다른 글
div 요소에서 svg 아래의 추가 공간을 제거하는 방법 (0) | 2020.11.10 |
---|---|
항상 클래스에 기본 생성자를 포함해야합니까? (0) | 2020.11.10 |
여러 bitbucket 계정 (0) | 2020.11.10 |
SQL Server에 2 백만 개의 행을 빠르게 삽입 (0) | 2020.11.10 |
AVD 하드웨어 버튼이 활성화되지 않음 (0) | 2020.11.10 |