I have a class Matrix which contains ArrayList<ArrayList<Double>> matrix; inside, and I want to know which is preferred when I want to copy instances of that class.
- Should I implement clone
- Use unmodifiable list HINT I don’t know how to do that on an ArrayList
- Do custom
copyEntries(){return Matrix(this);, and a copy constructor(Matrix other)
P.S
- I’m flexible if there was a better type recommendation like vector of vector
- if
List<List<Double>>and then newArrayList<Double>is that better ? - I’ve used Apache commons, and some other libs but at the end I found It should be custom made matrix class.
If what you try to do is to copy the matrix, bear in mind
Doubleis unmodifiable so, it doesn’t make much sense, creating new instances. You can freely copy the references using something like:List> copy = new ArrayList>();
copy.addAll( original );
Then you can modify any of the elements and the original won’t be changed:
Ok, I get my compiler and created a running sample to probe my point of not cloning the values.
Output:
It works!!