英文:
I need explain about initialized passing values to array as parameter
问题
在我学习Java中的哈希码(hashcode)时,我发现在Objects类中有一个名为hash的静态方法。这个方法接受一个Object数组作为参数,因此我们可以将不同类型的对象传递给这个方法,然后返回所有对象的组合哈希码。在java.util.Objects中,我们可以看到以下代码:
public static int hash(Object[] os) {
// 编译后的代码
}
我们可以像这样传递参数:
String name = "test";
int y = 55;
char c = 'A';
Objects.hash(name, y, c);
当我尝试创建一个接受Object数组作为参数的方法,并像这样传递值给这个方法时:
String name = "majd";
int y = 54;
TestClass.testMethod(name, y);
JVM给我报错了。我该如何修复这个问题?
英文:
When I am studying about hashcode in Java, I find in class Objects
static method name hash.
This method have an array of Object as parameter so we can pass different type of object to this method and return hashcode of compained of all objects. In
java.util.Objects
we can see :
public static int hash(Object[] os) {
// compiled code
}
and we can pass parameter like that
String name="test";
int y=55;
char c='A';
Objects.hash(name,y,c);
When I try to make a method which has an array of Object as parameter
and try pass values to this method like that
String name="majd";
int y=54;
TestClass.testMethod(name,y);
The JVM give me an error. How can I fix this?
答案1
得分: 2
你可以这样做。不要使用[](数组),而应该使用...(可变参数)。可变参数可以接受多个值。
public class Sample {
public static int testMethod(Object... os) {
// 在这里编写你的代码
return 0;
}
public static void main(String[] args) {
String name = "majd";
int y = 54;
Objects.hash(name, y);
Sample.testMethod(name, y);
}
}
英文:
You can do it this way. Instead of using [] (array) you should go for ... (variable arguments). Varargs can take number of values.
public class Sample {
public static int testMethod(Object... os) {
//your code here
return 0;
}
public static void main(String[] args) {
String name="majd";
int y=54;
Objects.hash(name,y);
Sample.testMethod(name,y);
}
}
答案2
得分: 1
Objects#hash
的方法签名实际上如下:
public static int hash(Object... values)
...
表示可变参数,这意味着可以传递任意数量的参数。
您的方法参数应该声明为 ...
而不是 []
(表示数组)。
public static void testMethod(Object... objects){
//do something
}
testMethod("abc", 123, new Object());//示例用法
英文:
Actually, the method signature of Objects#hash
looks like this:
public static int hash(Object... values)
The ...
signifies a variadic parameter, meaning that it can be called with as many arguments as one wants.
Your method parameter should be declared with ...
instead of []
(which signifies an array).
public static void testMethod(Object... objects){
//do something
}
testMethod("abc", 123, new Object());//example usage
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论