0

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.

  • I would guess: that method assumes that the target array has the same type. But Integer and int are **not** the same type. You could just manually iterate the vector, and turn the Integer objects into int values. But wondering: who told you to use Vector in the first place? – GhostCat Oct 06 '20 at 14:40
  • Why not use List/ArrayList all over the place What is the point of having data in a data structure, to then turn it into an array? – GhostCat Oct 06 '20 at 14:41
  • copyInto throws ArrayStoreException "if a component of this vector is not of a runtime type that can be stored in the specified array" Maybe you could say more about the problem you're trying to solve and then someone could opine on whether a Vector of Vectors is appropriate – MarkAddison Oct 06 '20 at 14:43

1 Answers1

0

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.

camickr
  • 321,443
  • 19
  • 166
  • 288