【问题标题】:How can I store vector of vectors into a 2d array in java [closed]如何在java中将向量的向量存储到二维数组中[关闭]
【发布时间】:2021-01-21 10:58:54
【问题描述】:

java代码中的sn-p在这里:

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);
    }
}
}

我想将向量vec 的元素存储在一个名为ar 的二维数组中。 我需要帮助来处理ArrayStoreException 并希望将vec 的元素存储到ar 中。 请帮忙。

【问题讨论】:

  • 我猜:该方法假定目标数组具有相同的类型。但 Integer 和 int 是同一类型。您可以手动迭代向量,并将 Integer 对象转换为 int 值。但想知道:谁让你首先使用 Vector?
  • 为什么不到处使用 List/ArrayList 数据结构中有数据,然后将其转换为数组有什么意义?
  • copyInto throws ArrayStoreException “如果此向量的组件不是可以存储在指定数组中的运行时类型”也许你可以多说一些关于你试图解决的问题然后有人可以就 Vector of Vectors 是否合适提出意见

标签: java vector arraystoreexception


【解决方案1】:

向量是一维的。数组是一维的。 Vector.copyInto() 方法将 i 维数组作为参数。

如果你想将一个向量的向量复制到一个 2 数组中,那么你需要遍历 2 个维度来进行复制

所以代码应该是这样的:

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;
}

我需要帮助来处理 ArrayStoreException

这是一个运行时异常。首先,您需要担心复制数据的正确算法。然后,如果您想捕获异常,您可以在整个算法中添加一个 try/catch 块。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-01
    • 2014-06-15
    • 2013-07-24
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多