Search code examples
javaconstructorextend

Java, passing not declared amount of arguments to array


What I'm writing a project to work with operations on vectors and here is where I got stuck at: I made superclass where I declare field coordinates and I have 3 different classes for different dimensions Vector3D, Vector5D, VectorND. At the end I faced a problem. This is superclass:

abstract class Vector implements sample
{       
    int[] coordinates;  
     public Vector (int[] coordinates)
     {
         this.coordinates=coordinates;
     }

Here is a Vector3D as an example:

class Vector3D extends Vector
{

public Vector3D(int n1,int n2,int n3) 
{
       super(new int[]{n1,n2,n3});
   }

And here is VectorND:

class VectorND extends Vector
{
    public VectorND(int...n) 
    {       
            super(new int[] {});
    }

And I'm wondering how I can pass not declared number of variables to constructor so when I call this method in main I can go this way : VectorND vec = new VectorND(1,2,3...n);? thanks for help!


Solution

  • You can just use n directly:

    public VectorND(int...n) 
    {       
        super(n);
    }
    

    Remember that variable argument lists in Java are (mostly) syntactic sugar for passing arrays.

    You know you can use n directly in this case because you know nothing else has a reference to that array, because it was created for the call to the VectorND constructor. (If you didn't know that, it would be safer to copy the array.)