How to display a multidimensional array without looping?

Asked

Viewed 543 times

5

When trying to run the section below:

int[] vetor = {1, 2, 3, 4, 5, 6};

System.out.println(Arrays.toString(vetor));

The array is normally displayed as [1, 2, 3, 4, 5, 6] but if I try with a two-dimensional array, as the section below:

int[][] matriz = {{1, 2, 3, 4, 5, 6}, {8, 10, 12, 14}};

System.out.println(Arrays.toString(matriz));

The result is [[I@7852e922, [I@4e25154f] and array values are not displayed.

Is there any way to display a direct two-dimensional array on System.out.println without having to loop or overwrite methods, as occurred in code with the simple array?

3 answers

9

Just use the method deepToString(Object[] a);

int array[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
System.out.println(Arrays.deepToString(array));

Exit:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

5


By both codes forEach with lambda, how much the method deepToString of Arrays utilize foreach and for respectively internally in their codes, there is no other way to display a array (simple or multidimensional) without that happens the loop. Concluding that without a loop, it is not possible to present in a text the data contained in a array, and the codes of classes can encapsulate this to be transparent to the developer, hiding (omitting) the reality of the code.

Codes:

forEach with lambda

@Override
public void forEach(Consumer<? super E> action) {
    Objects.requireNonNull(action);
    for (E e : a) {
        action.accept(e);
    }
}

deepToString

public static String deepToString(Object[] a) {
    if (a == null)
        return "null";

    int bufLen = 20 * a.length;
    if (a.length != 0 && bufLen <= 0)
        bufLen = Integer.MAX_VALUE;
    StringBuilder buf = new StringBuilder(bufLen);
    deepToString(a, buf, new HashSet<Object[]>());
    return buf.toString();
}

private static void deepToString(Object[] a, StringBuilder buf,
                                 Set<Object[]> dejaVu) {
    if (a == null) {
        buf.append("null");
        return;
    }
    int iMax = a.length - 1;
    if (iMax == -1) {
        buf.append("[]");
        return;
    }

    dejaVu.add(a);
    buf.append('[');
    for (int i = 0; ; i++) {

        Object element = a[i];
        if (element == null) {
            buf.append("null");
        } else {
            Class<?> eClass = element.getClass();

            if (eClass.isArray()) {
                if (eClass == byte[].class)
                    buf.append(toString((byte[]) element));
                else if (eClass == short[].class)
                    buf.append(toString((short[]) element));
                else if (eClass == int[].class)
                    buf.append(toString((int[]) element));
                else if (eClass == long[].class)
                    buf.append(toString((long[]) element));
                else if (eClass == char[].class)
                    buf.append(toString((char[]) element));
                else if (eClass == float[].class)
                    buf.append(toString((float[]) element));
                else if (eClass == double[].class)
                    buf.append(toString((double[]) element));
                else if (eClass == boolean[].class)
                    buf.append(toString((boolean[]) element));
                else { // element is an array of object references
                    if (dejaVu.contains(element))
                        buf.append("[...]");
                    else
                        deepToString((Object[])element, buf, dejaVu);
                }
            } else {  // element is non-null and not an array
                buf.append(element.toString());
            }
        }
        if (i == iMax)
            break;
        buf.append(", ");
    }
    buf.append(']');
    dejaVu.remove(a);
}

The example that step would be Java 8, with lambda:

int[][] matriz = {{1, 2, 3, 4, 5, 6}, {8, 10, 12, 14}};
Arrays.asList(matriz).forEach((i) -> { System.out.println(Arrays.toString(i)); });

Online Example

Reference:

  • The answer is valid and now it is even more complete (I have already left my vote), but regarding the need for tie, the question I addressed as to it is precisely that we do not have to write it, if the method makes the tie internally, as a native feature of language, you didn’t need to write it "in hand".

  • Understood @diegofm, neither of the two ways, need to write the for or foreach in the hand are methods (one with the very suggestive name) that internally is nothing more than a loop. When I was asked I wanted to pass this information in simple form so that everyone understands that we often look for some code and nothing more than to do it in a simple way. Thank you for the comment.

1

You must refer to the first array array, and the position you want and so on.

System.out.println(matriz[0][0]);//saida 1  
System.out.println(matriz[0][1]); //saida 2  
System.out.println(matriz[0][2]); //saida 3 
  • It is a valid solution, but is not very feasible depending on the size of the array, or the number of "sizes" it has.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.