How can I store vector of vectors into a 2d array in java

391 views Asked by At

The snippet in the java code is here:

public class MatrixUsingVectors {

    public static void main(String[] args) {
    
    Scanner sc= new Scanner(System.in);
    Vector<Vector<Integer> > vec= new Vector<Vector<Integer> >();
    for(int i=0;i<3;i++)
    {
        Vector<Integer> op= new Vector<Integer>(3);
        for(int j=0;j<3;j++)
        {
            op.add(sc.nextInt());
        }
        vec.add(op);
    }
    System.out.println(vec);
    int [][] ar= new int[vec.size()][3];
    vec.copyInto(ar);// this line throws ArrayStoreException
    for(int[] c: ar)
    {
        System.out.println(c);
    }
}
}

I want to store the elements of vector vec in a 2d array named ar. I need help to deal with ArrayStoreException and want to store the elements of vec into ar. Please help.

1

There are 1 answers

0
camickr On BEST ANSWER

Vector is 1 dimensional. Array is 1 dimensional. The Vector.copyInto() method takes a i dimensional array as a parameter.

If you want to copy a Vector of Vectors into a 2 Array, then you need to loop through the 2 dimensions to do the copy

So the code would be something like:

Object[][] rows = new Object[vec.size()][];

for (int i = 0; i < vec.size(); i++)
{
    Vector<Object> vectorRow = ((Vector)vec.get(i));
    Object[] arrayRow = new Object[vectorRow.size()];
    vectorRow.copyInto( arrayRow );
    rows[i] = arrayRow;
}

I need help to deal with ArrayStoreException

That is a run time Exception. First you need to worry about the proper algorithm to copy the data. Then if you want to catch the exception you add a try/catch block to the entire algorithm.