0

I could use help/direction on how to build a constructor that receives (for example 1, 2, 3) int's and stores them into an array object called arr2.

Part I:

public static void main (String[] args) {

Create an Arrays object using the first constructor
Arrays arr1 = new Arrays(5);


Arrays arr2 = new Arrays (1,2,3);
}

Part II:

public class Arrays {

private int [] array;
private int count;

public Arrays(int[] arr){

    int[] array = arr;
    array= arr;
    count = arr.length;
}}
Brian Wegner
  • 9
  • 1
  • 2
  • Probably you are looking for var args method parameter. – MGorgon Sep 27 '18 at 21:54
  • 1
    This is an interesting problem: if you call it as `int[] a = new int[] {1,2,3}; Arrays arr1 = new Arrays(a);` then you want to *copy* the passed-in array argument. But if you call it as `Arrays arr2 = new Arrays(1,2,3);` then you don't want to copy the array, because it would waste CPU time and memory, since you could just save a *reference* to the passed argument in the Arrays object. C++ already allows this optimization through rvalue references, but Java doesn't. You'll have to copy the array in every case even if you don't need to. – DodgyCodeException Sep 27 '18 at 21:57
  • your local variable `int[] array` hides the *member variable* that is also called `arrays`. To access the member variable instead, you'll have to reference it fully qualified with _this_: `this.array = arr`. – Alexander Sep 27 '18 at 21:59

2 Answers2

1

You could do it like this:

public class Arrays {

    private int [] array;

    public Arrays(int... arr){
        array = arr.clone();
    }

    public int get(int index) {
        return array[index];
    }
}

Changes from your code:

  1. The constructor uses varargs (look it up).
  2. There is no need to store the count; if you want the count the count, use array.length().
  3. The array is copied. This means you can change the original array that you passed in, but the values in the Arrays object won't be affected.
  4. I've added a getter method.
DodgyCodeException
  • 5,963
  • 3
  • 21
  • 42
0

Try use this constructor with var args

public Arrays(int... arr) {

    int[] array = arr;
    array= arr;
    count = arr.length;
}