【问题标题】:Returning an array without assign to a variable返回数组而不分配给变量
【发布时间】:2012-03-09 01:32:57
【问题描述】:

在java中有什么方法可以返回一个新数组而不先将它分配给一个变量? 这是一个例子:

public class Data {
    private int a;
    private int b;
    private int c;
    private int d;
    public int[] getData() {
        int[] data = { a, b, c, d };
        return data;
    }
}

我想做这样的事情,但不起作用:

public int[] getData() {
    return {a, b, c, d};
}

【问题讨论】:

标签: java arrays


【解决方案1】:

您仍然需要创建数组,即使您没有将其分配给变量。试试这个:

public int[] getData() {
    return new int[] {a,b,c,d};
}

您的代码示例不起作用,因为一方面,编译器仍然需要知道您尝试通过静态初始化 {} 创建的类型。

【讨论】:

    【解决方案2】:
    return new Integer[] {a,b,c,d}; // or
    return new int[] {a,b,c,d};
    

    【讨论】:

      【解决方案3】:
      public int[] getData() {
          return new int[]{a,b,c,d};
      }
      

      【讨论】:

        【解决方案4】:

        您已经构造了函数返回的对象,以下应该可以解决您的问题。

        public int[] getData() {
            return new int[]{a,b,c,d};
        }
        

        希望对你有帮助

        【讨论】:

          【解决方案5】:
          public class CentsToDollars {
          
              public static int[] getCentsToDollars(int cents) {
                  return new int[] { cents / 100, cents % 100 };
              }
          
              public static void main(String[] args) {
                  // TODO Auto-generated method stub
                  Scanner scan = new Scanner(System.in);
                  int cents;
                  System.out.print("Input the cents: ");
                  cents = scan.nextInt();
                  int[] result = getCentsToDollars(cents);
                  System.out.println("That is " + result[0] + " dollars and " + result[1] + " cents");
                  scan.close();
              }
          }
          

          【讨论】:

          • 虽然这可能会回答作者的问题,但它缺少一些解释性文字和/或文档链接。如果没有围绕它们的一些短语,原始代码 sn-ps 并不是很有帮助。您可能还会发现how to write a good answer 非常有帮助。请编辑您的答案 - From Review
          • 这似乎只是所有其他现有答案的重复。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-09-23
          • 2017-11-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多