在构造函数中动态初始化数组(Java)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7591182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:36:47  来源:igfitidea点击:

Initializing array on the fly in constructor (Java)

javaarraysconstructorinitialization

提问by user828835

 public class A{
      public A(int[] a){}
 }

 public class B extends A{
      public B(double[] b){
           super({b.length});  //ERROR
      }
 }

I want to be able to compile the code above. To clarify, I have class A and B that extends it. Class A does not have an empty parameter constructor. If I don't put a call to super in Class B's constructor on the first line, it will try to call super(), which doesn't exist. But, I want to call super(int[] a) instead. I want to do this by taking the length of a given double array and sending it as an array with length 1. It does not let me do this because apparently you can't declare an array like that, and if I were to declare it on a separate line it would call super() first and that won't work.

我希望能够编译上面的代码。澄清一下,我有扩展它的 A 类和 B 类。A 类没有空参数构造函数。如果我不在第一行的 B 类构造函数中调用 super,它将尝试调用不存在的 super()。但是,我想改为调用 super(int[] a) 。我想通过获取给定双数组的长度并将其作为长度为 1 的数组发送来做到这一点。它不允许我这样做,因为显然你不能声明这样的数组,如果我要声明它在单独的一行上,它会首先调用 super() 并且这行不通。

Is there any way to declare an int[] on the fly like that? Or are the only solution here to either make a constructor for A with no parameters or make my own function that returns an int[]?

有没有办法像这样动态地声明一个 int[] ?或者这里唯一的解决方案是为 A 制作一个没有参数的构造函数,或者制作我自己的返回 int[] 的函数?

(Don't ask why I want to send it as an array like that.)

(不要问我为什么要把它作为这样的数组发送。)

回答by corsiKa

If you insist on not asking why...

如果你坚持不问为什么...

You could make the array, assign the first and only element and send it.

您可以创建数组,分配第一个也是唯一的元素并发送它。

public class B extends A{
      public B(double[] b){
           int[] arr = new int[1];
           arr[0] = b.length;
           super(arr);  // broken, super must be first.
      }
}

This means you must have a one line solution. Luckily, Java provides an in-line way to make a series of elements into an array at compile time.

这意味着您必须有一个单行解决方案。幸运的是,Java 提供了一种在编译时将一系列元素组成数组的内联方法。

public class B extends A{
      public B(double[] b){
           super(new int[]{b.length});  // FIXED
      }
}

回答by irreputable

you can also

你也可以

 public class A{
    public A(int... a){}
 }

 public class B extends A{
    public B(double[] b){
       super( b.length ); 
  }
 }

回答by OscarRyz

Yeap, try:

是的,试试:

 super(new int[]{b.length});  //ERROR NO MORE