【问题标题】:Is there a way to somehow extract an int[ ] array value from a method that returns a void?有没有办法以某种方式从返回 void 的方法中提取 int[] 数组值?
【发布时间】:2017-07-05 03:45:12
【问题描述】:

如果我有以下代码修改创建的数组并仅返回 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.
    }

【问题讨论】:

  • 抱歉,anArray() 打错了。应该是createArray()
  • 不要用 cmets 修正错别字,edit你的帖子。
  • 处理输入参数似乎不是一种安全的方法。此外,如果您使用全局类变量,您将无法从不同的地方使用您的类,因为您的全局变量将被共享
  • Void 实际上不是数据类型(对象或原始数据)。数组是一个对象,您传递的是对象引用的值或原语的值。您需要更改 modifyArray 方法以返回数组。否则您将如何编码知道对数组的引用是什么?
  • 您遗漏了一些信息,如果您多次调用相同的函数(使用相同的参数)会有区别吗?使用 Map 存储由int n 标识的数组,您将能够使用 getter 获取它。当然,这仍然会将您限制为每个参数值一个数组。 returns it as a void,不,你不会用void返回任何东西。

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 小心,这些是static method
    【解决方案3】:
    public static void modifyArray() {
        int[] a = createArray(1);
        myFunction(a);
        // Whatever you want to do with a
    }
    

    【讨论】:

    • 这并不能真正回答问题。
    • 对不起...下次我会用我的话:)
    猜你喜欢
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    • 2019-08-29
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多