Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing array on the fly in constructor (Java)

 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.

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[]?

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

like image 441
user828835 Avatar asked Sep 29 '11 00:09

user828835


2 Answers

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.

public class B extends A{
      public B(double[] b){
           super(new int[]{b.length});  // FIXED
      }
}
like image 58
corsiKa Avatar answered Nov 13 '22 21:11

corsiKa


you can also

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

 public class B extends A{
    public B(double[] b){
       super( b.length ); 
  }
 }
like image 40
irreputable Avatar answered Nov 13 '22 19:11

irreputable