Print arrays in Java

↘锁芯ラ 提交于 2019-12-05 04:19:31

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]

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.

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]"

You need to use reflection to get to the deeper structure of an Object if you don't want to rely on object's class itself to overload the Object toString method (to get something more useful than printing class name and hash code...)

My suggestion is to use a library that uses reflection to get to the deeper structure, such as GSON: http://code.google.com/p/google-gson/

public static String print(Object object) {
    return new Gson().toJson(object);
}

public static void test() {
    System.out.println(print(new int[][] {new  int[] {1, 2, 3} }));
    // outputs: [[1,2,3]]
    System.out.println(print(new String[] { "aa", "bb", "cc" }));
    // outputs: ["aa","bb","cc"]
}

This prints arrays effortlessly, including multi-dimensional arrays and primitive arrays.

But the real benefit is that it prints objects of any class in a uniform way, whether the class has overriden toString in any useful way or not.

If all you want to do is print it out as a String, why cast it? Just treat it as an array of Objects, iterate through the array, and the call the toString() method on each Object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!