Search code examples
javaarrayscastingprimitive-types

How to convert 2-dimensional double array from 2-dimensional Integer array in Java


I am trying to create a utility function to create a 2-dimensional array of doubles out of a 2-dimensional array of Integers (which is created from deeplearning4j's KerasTokenizer's textsToSequences(String[] texts) method). I created the method below but keep getting NullPointerExceptions at line 111 (doubles[i][j] = list.get(j);). How can I change my method or create a new one to fix this problem?

public static double[][] integerToDoubleArray(Integer[][] integers) {
        double[][] doubles = new double[integers.length][];
        for (int i = 0; i < integers.length; i++) {
            List<Integer> list = Arrays.asList(integers[i]);
            for (int j = 0; j < list.size(); j++) {
                doubles[i][j] = list.get(j);
            }
        }
        return doubles;
    }

I call it using the following method with the following API: https://deeplearning4j.org/api/latest/org/deeplearning4j/nn/modelimport/keras/preprocessing/text/KerasTokenizer.html#textsToSequences-java.lang.String:A-

private static double[][] encodeSequences(KerasTokenizer tokenizer, int length, ArrayList<String> sentences) {
        return integerToDoubleArray(tokenizer.textsToSequences(arraylistToArray(sentences)));
    }

Solution

  • You did not specify the second dimension of doubles (which is an array of double arrays), nor did you initialize each element of it, so you are getting this exception. Just initialize each row to a new double array with the length of the integer array at that index.

    public static double[][] integerToDoubleArray(Integer[][] integers) {
        double[][] doubles = new double[integers.length][];
        for (int i = 0; i < integers.length; i++) {
            doubles[i] = new double[integers[i].length];
            List<Integer> list = Arrays.asList(integers[i]);
            System.out.println(list);
            for (int j = 0; j < list.size(); j++) {
                doubles[i][j] = list.get(j);
            }
        }
        return doubles;
    }
    

    It should be noted that you do not need to convert each row of the two dimensional Integer array to a List, as you can simply use integers[i][j] to access the element at row i and column j. Demo

    public static double[][] integerToDoubleArray(Integer[][] integers) {
        double[][] doubles = new double[integers.length][];
        for (int i = 0; i < integers.length; i++) {
            doubles[i] = new double[integers[i].length];
            for (int j = 0; j < integers[i].length; j++) {
                doubles[i][j] = integers[i][j];
            }
        }
        return doubles;
    }