我发现了几个如何反转数组的线程。但是,我不明白为什么不能对静态方法和 void 方法使用相同的代码。
有人可以解释一下以下示例中的差异吗?
对于静态方法我们可以这样写:
public static double[] reverse (double[] a)
{
int n = a.length;
for (int i = 0; i < n/2; i++)
{
double temp = a[i];
a[i] = a[n-(i+1)];
a[n-(i+1)] = temp;
}
return a;
}
但是对于静态空,我们有:
public static void reverse (double[] a)
{
for (int i = 0, j = a.length-1; i < j; i++, j--)
{
double temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
最佳答案
首先,您的情况下的两种方法都是静态的。他们只是有不同的返回类型
对于 static void reverse (double[] a)
情况,您可以这样做:
double[] arr = //some array
reverse(arr); //at this point arr is reversed so that you can use it
reversedArr = arr; //or assign to different variable
实际上,如果你必须反转一些内部数组,但我仍然不喜欢它,因为数组的更改不太明显。我认为公开这样的方法不太好......
static double[] reverse (double[] a)
很适合成为某些实用程序类的一部分,即
double[] arr = //some array
reversedArr = ArrayUtils.reverse(arr); // now you can reuse method and you actually see that you changed the array
但是您应该修改方法以不更改初始数组,因为您可能会遇到麻烦(调用实用程序方法不应修改初始值)
关于java - 用静态方法反转数组 VS static void?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54536737/