How can you convert a 2 dimensional array into a 1 dimensional array in Java

前端 未结 4 1186
伪装坚强ぢ
伪装坚强ぢ 2020-12-18 07:02

I would like to know how to convert a 2 dimensional array into a 1 dimensional array. I have come up with some code but it doesn\'t exactly seem to work. Can someone please

4条回答
  •  醉梦人生
    2020-12-18 07:43

    The length of the 1-dimensional array must be the sums of the lengths of all rows in the 2-dimensional array. Of course, Java doesn't really have "true" 2-dimensional arrays, but arrays of arrays. This code works, and is wrapped in a simple demo program.

    public class ArrayFlattening {

    public static final String[][] STRINGS2 = {
        {"my", "dog", "has", "fleas"},
        {"how", "now", "brown", "cow"},
        {"short", "row"},
        {"this", "is", "a", "final", "row", "in", "this", "test"},
    };
    
    public static String[] flatten(String[][] a2) {
        String[] result = new String[totalSize(a2)];
        int index = 0;
        for (String[] a1 : a2) {
            for (String s : a1) {
                result[index++] = s;
            }
        }
        return result;
    }
    
    public static int totalSize(String[][] a2) {
        int result = 0;
        for (String[] a1 : a2) {
            result += a1.length;
        }
        return result;
    }
    
    public static void main(String[] args) {
        System.out.println("" + STRINGS2.length + " rows");
        for (String[] strings1 : STRINGS2) {
            System.out.println("" + strings1.length + " strings");
            for (String s : strings1) {
                System.out.print("\t" + s);
            }
            System.out.println();
        }
        String[] strings1 = flatten(STRINGS2);
        System.out.println(strings1.length + " strings");
        for (String s : strings1) {
            System.out.print("\t" + s);
        }
        System.out.println();
    }
    

    }

提交回复
热议问题