我想从routedClients
删除array
中的元素,因此我将其转换为ArrayList
,然后使用remove
,最后我将其转换回double[][]
{1}}数组。但是当我执行它时,它给了我关于这一行的消息:
double[][] remainingStockout = (double[][]) stockout.toArray();
错误是:
线程中的异常" main" java.lang.ClassCastException:[Ljava.lang.Object;无法转换为[[Ljava.lang.Double;
任何帮助都会非常感激。 :)
public double[][] removeSite(double[][] array) {
List<double[]> stockout = new ArrayList<double[]>(Arrays.asList(array));
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < routedClients.size(); j++) {
if (array[i][0] == routedClients.get(j)) {
stockout.remove(i);
}
}
}
double[][] remainingStockout = (double[][]) stockout.toArray();
return remainingStockout;
}
答案 0 :(得分:3)
以下似乎有效
require
全班测试:
double[][] remainingStockout = (double[][]) stockout.toArray(new double[][]{});
这是输出
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
static ArrayList<Double> routedClients = new ArrayList<Double>();
public static void main(String[] args) {
double[][] arr1 = { { 2, 4, 6 }, { 3, 6, 9 }, { 5, 10, 15 } };
routedClients.add(new Double(1));
routedClients.add(new Double(2));
routedClients.add(new Double(3));
print(arr1);
double[][] arr2 = removeSite(arr1);
print(arr2);
}
private static void print(double[][] arr1) {
for (int i = 0; i < arr1.length; i++) {
double[] arr2 = arr1[i];
for (int j = 0; j < arr2.length; j++) {
System.out.println("arr1[" + i + "][" + j + "] = " + arr1[i][j]);
}
}
}
public static double[][] removeSite(double[][] array) {
List<double[]> stockout = new ArrayList<double[]>(Arrays.asList(array));
System.out.println("length before = " + stockout.size());
for (int i = array.length-1; i >= 0; i--) {
for (int j = 0; j < routedClients.size(); j++) {
if (array[i][0] == routedClients.get(j)) {
System.out.println("removing " + routedClients.get(j));
stockout.remove(i);
}
}
}
double[][] remainingStockout = (double[][]) stockout.toArray(new double[][] {});
System.out.println("length after = " + remainingStockout.length);
return remainingStockout;
}
}
答案 1 :(得分:1)
您正在尝试将对象强制转换为数组。
这不可能。
相反,您需要转换数组中的每个元素,然后需要将它添加到2D数组中。
以下行永远不会有效:
double[][] remainingStockout = (double[][]) stockout.toArray();
答案 2 :(得分:0)
您可以将双数组转换为列表数组,因为编译器只生成包含所有元素的列表,但编译器无法知道制作2D数组的大小。
也许您可以尝试创建列表列表。但是,您需要再次遍历阵列两次。一个用于将值分配给嵌套列表,然后在返回值之前将它们再次分配给double数组。
答案 3 :(得分:0)
你可以使用toArray()的重载方法..像这样 -
double[][] remainingStockout = new double[array.length][array.length];
stockout.toArray(remainingStockout);