javamultiple-constructors

Java: Multiple constructors forcing code reuse?


I have a class where one of its members is ArrayList<ArrayList<Double>> elements, and so I have a constructor that takes in that same type and all is good.

public elementArray(ArrayList<ArrayList<Double>> elements)
{
    this.elements =  elements;
    // a bunch of other stuff happens
}

However, I also need to be able to construct with an input of type Double[][], so I first convert it to the 2D list type, and then call the original constructor...

public elementArray(Double[][] array)
{
    // convert Double[][] array to ArrayList<ArrayList<Double>> elements
    this(elements);
}

Only, I can't call another constructor except as the first thing that happens in my constructor! Am I doomed to copy-paste here, or is there a clever way to do what I want?


Solution

  • One solution would be to extract the conversion into a static method:

    public elementArray(Double[][] array) {
        this(convert(elements));
    }
    
    private static ArrayList<ArrayList<Double>> convert(Double[][] array) {
        // convert Double[][] array to ArrayList<ArrayList<Double>> elements
    }