我找到了几个线程如何反转数组。但是,我不遵循为什么不能为静态方法和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
但是你应该修改一个不改变初始数组的方法,因为你可能会遇到麻烦(调用实用程序方法不应该修改初始值)