开发者

java beginner: which is preferred when class has arraylist of arraylist (clone(), unmodifiable list,custom deepcopying)

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.

  1. Should I implement clone
  2. Use unmodifiable list HINT I don't know how to do that on an ArrayList
  3. Do custom copyEntries(){return Matrix(this); , and a copy constructor (Matrix other)

P.S

  1. I'm flexible if there was a better type recommendation like vector of vector
  2. if List<List<Double>> and then new ArrayList<Double> is that better ?
  3. 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 Double is 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:

copy.get( 0 ) .get( 0 ) = -1.0; 

// original at ( 0,0 ) remains the same ... 

Ok, I get my compiler and created a running sample to probe my point of not cloning the values.

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class CopyMatrix { 
    public static void main( String [] args ) { 

        Matrix m = new Matrix();
        m.add( Arrays.asList(0.0, 1.0, 2.0 ));
        m.add( Arrays.asList(3.0, 4.0, 5.0 ));
        m.add( Arrays.asList(6.0, 7.0, 8.0 ));

        System.out.println("m = \n" +  m );

        Matrix m1 = m.copy() ;

        m1.get( 0 ).set( 0 , 100.0 );
        m1.get( 2 ).set( 2 , -400.0 );


        System.out.printf( "After m = %n %s %n m1 = %n %s %n", m, m1);
    }
}
class Matrix extends ArrayList<List<Double>> {
    public Matrix copy() {
        Matrix copy = new Matrix();
        for( List<Double> each : this ) { 
            copy.add( new ArrayList<Double>( each ) );
        }
        return copy;
    }
}

Output:

 java CopyMatrix 
m = 
[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]
After m = 
 [[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]] 
 m1 = 
 [[100.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, -400.0]] 

It works!!


I would probably use

class Matrix implements Cloneable {

Then, in the clone method:

matrix = new ArrayList<ArrayList<Double>>(other.matrix.size());
for(ArrayList<Double> vector:other.matrix){
    matrix.add(vector.clone());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜