'Fruit...' 是 Java 命名约定中的有效 class 名称吗?
Is 'Fruit...' a valid class name in Java Naming convention?
我是 Java 的初学者,在我探索的过程中,我看到了一段代码,其用法如 Fruit... fruitName
?我曾在 ...
等任何文档中看到过这种用法
有谁知道这个的用途和用法吗?
class Fruit {
// Class implementation
}
public void extractJuice(Fruit... args) {
// This method can take variable arguments of type Fruit
}
所以你看到的是可变参数的缩写。
更多参考资料:
- When do you use varargs in Java?
在 Java 中的 class 名称中唯一可以包含的是任何大小写的字母、数字(尽管 class 名称不能以数字开头) 和下划线。
省略号 (...
) 可以跟在 class 名称后的唯一情况是当您指定 class 的可变参数列表时。
考虑函数foo
,定义
void foo(Fruit... fruits){
for (fruit : fruits){
/*each argument considered here*/
}
}
foo
可以用任意数量的 Fruit
实例调用。
valid characters in a java class name
... 也用于 Java。它被称为可变参数。当你想得到一些具有相同类型的参数,但参数的数量不确定时使用它。它也在 C 中使用。想想 scanf/printf 函数。
不,Java 中的 class 名称不能包含 .
字符。
...
语法是一种声明方法的方法,该方法从给定类型接收任意数量的参数(并在内部将它们视为数组。
例如:
public void printAllFruits (Fruit... fruits) {
// fruits is a Fruit[]:
for (Fruit fruit : fruits) {
System.out.println(fruit);
}
}
public static void main(String[] args) {
Fruit f1 = new Fruit("apple");
Fruit f2 = new Fruit("pear");
Fruit f3 = new Fruit("banana");
// This would work:
printAllFruits(f1);
// And so will this:
printAllFruits(f1, f2, f3);
}
我是 Java 的初学者,在我探索的过程中,我看到了一段代码,其用法如 Fruit... fruitName
?我曾在 ...
有谁知道这个的用途和用法吗?
class Fruit {
// Class implementation
}
public void extractJuice(Fruit... args) {
// This method can take variable arguments of type Fruit
}
所以你看到的是可变参数的缩写。
更多参考资料: - When do you use varargs in Java?
在 Java 中的 class 名称中唯一可以包含的是任何大小写的字母、数字(尽管 class 名称不能以数字开头) 和下划线。
省略号 (...
) 可以跟在 class 名称后的唯一情况是当您指定 class 的可变参数列表时。
考虑函数foo
,定义
void foo(Fruit... fruits){
for (fruit : fruits){
/*each argument considered here*/
}
}
foo
可以用任意数量的 Fruit
实例调用。
valid characters in a java class name
... 也用于 Java。它被称为可变参数。当你想得到一些具有相同类型的参数,但参数的数量不确定时使用它。它也在 C 中使用。想想 scanf/printf 函数。
不,Java 中的 class 名称不能包含 .
字符。
...
语法是一种声明方法的方法,该方法从给定类型接收任意数量的参数(并在内部将它们视为数组。
例如:
public void printAllFruits (Fruit... fruits) {
// fruits is a Fruit[]:
for (Fruit fruit : fruits) {
System.out.println(fruit);
}
}
public static void main(String[] args) {
Fruit f1 = new Fruit("apple");
Fruit f2 = new Fruit("pear");
Fruit f3 = new Fruit("banana");
// This would work:
printAllFruits(f1);
// And so will this:
printAllFruits(f1, f2, f3);
}