1

Need some advice for a project in an intro Java class. I'm stuck at creating a assignment constructor which takes an array as input and completes a deep copy. The constructor in question is found in the second block of code.

import java.util.Scanner;

public class NumberList
{
    public static final int MAX_CAPACITY = 100;

    private double [] numbers;  

    private int length;


    public NumberList()
    {
       numbers = new double[MAX_CAPACITY];
       int i;

       for(i = 0; i < MAX_CAPACITY; i++)
         numbers[i] = 0;

         length = 10;
    }

Everything before this line compiles. The constructor below is to complete a deep copy from the array parameter to the numbers array.

    NumberList(final double a[])
    {
        double a[] = new double[MAX_CAPACITY];
        numbers = a[];
    }

Following errors received:

NumberList.java:67: error: '.class' expected
        numbers = a[];

For the life of me, I cannot figure out how to do fix this. I've tried with a "for" loop, as well.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
bap
  • 75
  • 1
  • 1
  • 5

3 Answers3

1

Just run over a and copy its elements to numbers:

public NumberList(final double[] a) {
    this.numbers = new double[a.length];
    for (int i = 0; i < a.length; ++i) {
        this.numbers[i] = a[i];
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1
NumberList(final double a[])
{
    double a[] = new double[MAX_CAPACITY];
    numbers = a[];
}

The first line is attempting to re-declare the parameter a; you can't do that.

And the second line uses an invalid syntax: you never use [] except in the declaration of array variables, or the initialization of those variables.

The easiest way to copy a is to write:

numbers = Arrays.copyOf(a, a.length);

But you can write this with a loop like Mureinik shows you.


Note that you should write double[] a, not double a[]. The two are semantically identical, but the former is preferred because [] is part of the type, not the variable name.

The double a[]-style was put into Java "as a nod to the tradition of C and C++". You can read more here.

Community
  • 1
  • 1
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

You can simply use:

NumberList(final double[] a) {
    numbers = Arrays.copyOf(a, a.length);
}
Naruto Biju Mode
  • 2,011
  • 3
  • 15
  • 28