7

I'm writing a method that prints every Object that is passed to it. This works fine by calling the Object.toString() method for the object but doesn't work 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));
7
  • 1
    This question is similar to: What's the simplest way to print a Java array?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Aug 17 at 7:10
  • @camilajenny No it is not, this question asks something else. Commented Aug 17 at 9:24
  • @MarkRotteveel first of all, correct the title. there are 100 posts about printing arrays in Java @ SO, with such a sloppy title the question should be closed immediately as is Commented Aug 19 at 11:03
  • @camilajenny The title alone does not decide if a question is a duplicate or not. This question is about asking how you can call Arrays.toString if all you have is an Object holding the array, and that is definitely not answered by the duplicate you proposed. Commented Aug 19 at 11:03
  • @camilajenny And if you think the title is not good enough, then you should edit it, not just close. Commented Aug 19 at 11:04

5 Answers 5

12

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]
Sign up to request clarification or add additional context in comments.

7 Comments

How could I find out if it's an primitive array? Also I need to know the primitive type of the array.
Pls check the updated code, it will now print any array object without needing you to cast to every primitive type in an ugly chain of if/elseif/else
Interesting update, though the added expense of reflection and autoboxing is worth mentioning.
@PaulBellora I have read tons of articles cautioning against using so called "expensive" Reflection but have also seen almost every modern framework making good use of it. Read this for ex: buzdin.blogspot.com/2011/01/is-java-reflection-really-slow.html My 2 cents: Make sure you have a good usecase to use reflection and IMHO this question was good fit for that.
Brilliant, just what I needed.
|
1

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.

Comments

1

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

Comments

0

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.

Comments

-2

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.

1 Comment

But I can't cast it to an Object array if it contains primitive types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.