0

The class java.util.Objects contains the deepEquals(Object a, Object b) method that can be used to compare objects of any type (including arrays and null references), but doesn't contain a similar deepToString(Object o). This is disappointing. (By the way, the private constructor of this class contains the message "No java.util.Objects instances for you!" that explains to some extent why this class is so mean). That being the case, I've tried to implement the method myself:

public static String deepToString(Object o) {
    if (o == null || !o.getClass().isArray())
        return Objects.toString(o);
    else
        return Arrays.deepToString((Object[])o);
}

The problem is that it doesn't work with one-dimensional arrays of primitive types. Do I have to go through all primitive array types with nested else ifs and call corresponding Arrays.toString(...) methods for them, or there is a simpler alternative?

John McClane
  • 3,498
  • 3
  • 12
  • 33
  • If there was a generic way to do that, there wouldn't be specific `Arrays.toString` methods for different primitive array types. Note the method bodies are verbatim copies of each other. – pafau k. Jun 04 '20 at 12:06
  • Or, if you're fine with committing atrocities, [see how to rewrite any primitive array as boxed one with reflection](https://stackoverflow.com/a/3775583/1384908) – pafau k. Jun 04 '20 at 12:13

1 Answers1

1

I came to this solution: wrap a primitive array into Object[] and remove the outer brackets from the result returned by the public Arrays.deepToString(Object[] a):

public static String deepToString(Object o) {
    if (o == null || !o.getClass().isArray())
        return Objects.toString(o);
    else if (o instanceof Object[])
        return Arrays.deepToString((Object[])o);
    else {
        String s = Arrays.deepToString(new Object[] { o });
        return s.substring(1, s.length() - 1);
    }
}

Not very efficient, because it could create two large strings instead of a single one. But with this trick, I can use the hidden

Arrays.deepToString(Object[] a, StringBuilder buf, Set<Object[]> dejaVu)

method that contains the primitive arrays parsing logic.

John McClane
  • 3,498
  • 3
  • 12
  • 33
  • It could just be `String s = Arrays.deepToString(new Object[] {o}); return s.substring(1, s.length()-1);`? –  Aug 24 '20 at 09:16
  • @saka1029 Yes, but it would be slower for `null`s, non-arrays, arrays of non-primitive types and multidimensional arrays of primitive types. – John McClane Aug 24 '20 at 18:32