Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print arrays in Java

I'm writing a method that prints every Object it get passed. This works fine by calling the Object.toString() method for the object but doesn't works for arrays. I can find out whether it is an Array with the Object.getClass().isArray() method, but I don't know how to cast it.

int[] a;
Integer[] b;

Object aObject = a;
Object bObject = b;

// this wouldn't work
System.out.println(Arrays.toString(aObject));
System.out.println(Arrays.toString(bObject));
like image 291
multiholle Avatar asked Jan 18 '12 19:01

multiholle


People also ask

How do I print an array format?

Print an Array Using Arrays. toString() and Arrays. deepToString() The built-in toString() method is an extremely simple way to print out formatted versions of objects in Java.

How do I print multiple arrays?

To print the content of a one-dimensional array, use the Arrays. toString() method. To print the content of a a multi-dimensional array, use the Arrays. deepToString() method.

How do I print an int array?

In order to print an integer array, all you need to do is call Arrays. toString(int array) method and pass your integer array to it. This method will take care of the printing content of your integer array, as shown below. If you directly pass int array to System.


3 Answers

If you don't know the type you can cast the object to Object[] and print it like this (after making sure it is indeed an array and can be cast to Object[]). If it is not an instance of Object[] then use reflection to create an Object[] first and then print:

private void printAnyArray(Object aObject) {
    if (aObject.getClass().isArray()) {
        if (aObject instanceof Object[]) // can we cast to Object[]
            System.out.println(Arrays.toString((Object[]) aObject));
        else {  // we can't cast to Object[] - case of primitive arrays
            int length = Array.getLength(aObject);
            Object[] objArr = new Object[length];
            for (int i=0; i<length; i++)
                objArr[i] =  Array.get(aObject, i);
            System.out.println(Arrays.toString(objArr));
        }
    }
}

TESTING:

printAnyArray(new int[]{1, 4, 9, 16, 25});
printAnyArray(new String[]{"foo", "bar", "baz"});

OUTPUT:

[1, 4, 9, 16, 25]
[foo, bar, baz]
like image 91
anubhava Avatar answered Oct 23 '22 05:10

anubhava


If you're asking how you can call this method programmatically on any array, it's not going to be possible with primitive arrays. Looking at the docs for the Arrays class, you'll see there's an overload of toString() for every primitive array type.

This is because int[] for example extends Object rather than Object[].

EDIT: here's a regrettably longwinded solution to include primitive arrays:

public static void printObject(Object obj) {

    String output;

    if (obj == null) {
        output = "null";
    }
    else if (obj.getClass().isArray()) {

        if (obj instanceof Object[]) {
            output = Arrays.toString((Object[])obj); //Object[] overload
        }
        else if (obj instanceof int[]) {
            output = Arrays.toString((int[])obj);    //int[] overload
        }
        //and so on for every primitive type
    }
    else {
        output = obj.toString();
    }

    System.out.println(output);
}

I'm hoping someone else can provide a more elegant solution, but based on the limitations of primitive arrays, this might be the best you can do.

like image 37
Paul Bellora Avatar answered Oct 23 '22 05:10

Paul Bellora


Why don't you let method overloading solve your problem? Simply write two (or more) methods with the same name but different signatures and then let the compiler decide which method will be called when the program executes:

void print(Object object) {
   System.out.println("Object: " + object);
}

void print(Object[] array) {
    System.out.println("Object[]: " Arrays.toString(array)); 
}

void print(int[] array) {
    System.out.println("int[]: " Arrays.toString(array)); 
}

Example usage elsewhere in the code:

String first = "test";
print(first);   // prints "Object: test";

String[] second = {"A", "B"};    
print(second);   // prints "Object[]: [A, B]" 

int[] third = {1, 2};
print(third);    // prints "int[]: [1, 2]"
like image 1
matsev Avatar answered Oct 23 '22 04:10

matsev