Search code examples
javaarraysconstructorsettercustom-exceptions

java array fixed element for constructor


I'm writing my firsts classes in java.

I did a class with an int[] that must be declared with 3 elements.

public abstract class MyClass {
   private String name;
   private int[] myValues = new int[2];

now my question is:

  1. what is the best way to ensure that user must insert every member?

Then.. The constructor would be the best way to do that, so I did the constructor with every single element clearly required:

public MyClass(String nam, int val0, int val1, int val2){
   int[] values = new int[]{val0, val1, val2};
   setMyValues(values);
}

private void setMyValues(int[] vals){
   this.myValues = vals;
}
  1. it's a good practice? seems to be complicated instead of giving a simple array as:

    public void MyClass(int[] vals)..
    

    but in this way I can't be sure about number of elements.I should create a custom-exception or an if(vals.length != 2) cicle..

I've some other doubts:

  1. is useful to declare myValues = new int[2] or it's the same simply writing int[] myValues? (why declare number of elements in the inner state?)

  2. it's better to receive parameters from constructor or pass a vector to setter (setMyValues(int[] vals)) and check array in setter?

tank you for every suggestion.


Solution

    1. You could have a overloaded constructor, one with the three integer values and one with the array. On the first one build an array and pass it to the array constructor, inside the second constructor call the setter and evaluate the length, if is longer than three throw the exception.
    2. You're allocating an object which is never used, wastes space and is going to be collected by the GC after the new array is assigned. I'd assign nothing to that property.
    3. It depends upon your approach. You can go for the first point and add a third default constructor, then set the array using the setter method.

    Hope this help.