Majda Benaomar Majda Benaomar - 2 months ago 9
Java Question

Remove elements from 2D array

I want to remove elements that are in

routedClients
from
array
, so I converted it to an
ArrayList
, then used
remove
, finally I converted it back to
double[][]
array. But when I execute it, it gives me this message about this line:

double[][] remainingStockout = (double[][]) stockout.toArray();


The error is:


Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [[Ljava.lang.Double;


Any help would be really appreciated. :)

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;

}

Answer

The below appears to work

double[][] remainingStockout = (double[][]) stockout.toArray(new double[][]{});

Full class for testing:

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

        double[][] arr2 = removeSite(arr1);

    }

    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 = 0; i < array.length; 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;
    }
}
Comments