有没有办法以某种方式从返回void的方法中提取int []数组值?

时间:2017-02-16 07:00:48

标签: java arrays return-value void return-type

如果我有以下代码修改创建的数组并仅返回 void

 public static void modifyArray()
{
      myFunction(createArray(1));
}

其中createArray()只是一些生成数组的函数,如下所示:

 public static int[] createArray(int n)
 {
      //Lines of code that generate an array;
 }

myFunction()只是一些修改数组并将其作为void返回的任意函数:

 public static void myFunction(int[] anArray)
 {
      //Lines of codes that modifies any int[] array passed to this function;
 }

如何使用另一个函数将modifyArray()函数中的修改后的数组作为 int [] 返回,而不将myFunction()的返回类型更改为int [ ],例如:

    public static int[] convertModifiedArray()
    {
           return modifyArray(); //This is an error since modifyArray() is a void, not an int[].  I just don't know a way to somehow "translate" a void into an int[] and I need help with this part.
    }

3 个答案:

答案 0 :(得分:2)

您可以将返回类型更改为int [] 或者,您可以创建一个全局变量,并在方法中设置该值。

答案 1 :(得分:1)

您可以在类中声明类似int [] myArray的实例变量。在modifyArray函数中,您可以将myArray分配给已修改的数组。您将在myArray中获得修改后的数组,无需更改方法的返回类型。

答案 2 :(得分:-2)

public static void modifyArray() {
    int[] a = createArray(1);
    myFunction(a);
    // Whatever you want to do with a
}