来自字符串数组的通用NxM矩阵

时间:2017-12-14 10:21:10

标签: java arrays generics matrix

目的是从字符串数组创建NxM矩阵,例如:

String[] arrayOfStrings = new String[] {"1 2 3","4 5 6"}

然后输出矩阵

Integer[][] matrix = new Integer[][] { {1,2,3},{4,5,6}}

变压器应该足够通用,它可以产生Double,Integer矩阵......

对于1维我能够做到。这是代码:

    /**
     * Construct a matrix row from string line
     * Example:
     * in  = "1.7 5.14 9"
     * out = new Double[] { 1.7 ,5.14,9}
     *
     * @param in               string to lineToRow
     * @param compatibleParser specialize parser
     * @param <E>              type
     * @return matrix row
     */
    public static <E> E[] lineToRow(String in, Function<String, E> compatibleParser) {
        final String[] els = in.split(" +"); /* ignore multiple spaces */
        final E[] res = (E[]) new Object[els.length];
        int i = 0;
        for (String s : els) {
            res[i] = compatibleParser.apply(s);
            i++;
        }
        return res;
    }

对它的测试如下:

    @Test
    public void stringLineToMatrixRow() {

        String line0 = "1 2 3";
        Assert.assertArrayEquals(new Integer[]{1, 2, 3}, MatrixUtils.lineToRow(line0, Integer::parseInt));
        Assert.assertArrayEquals(new Double[]{1.7, 2.99, 3.8}, MatrixUtils.lineToRow("1.7   2.99 3.8", Double::valueOf));
    }

对于2个dims,我唯一的成功是“硬编码”类型,请参见例:

   /**
     * TODO find a way to use something like E[][]
     */
    public static Double[][] lineToRow(String[] ins) {
        int i = 0;
        Double[][] res = new Double[ins.length][3]; //3 just for test
        for (String ss : ins) {
            int j = 0;
            final String[] els = ss.split(" +");
            for (String s : els) {
                res[i][j] = Double.valueOf(s);
                j++;
            }
            i++;
        }
        return res;
    }

它适用于1个暗淡的数组,因为这一行(来自示例1)没问题:

  

final E [] res =(E [])new Object [els.length];   但不适用于E [] [] ......

注意:这是从它的Communauty建议的codereview.stackexchange迁移的

0 个答案:

没有答案