我需要解释关于将初始化的值传递给数组作为参数。

huangapple go评论154阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年8月8日 23:08:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63316915.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定