Objects.deepToString(Object o) method

前端 未结 1 981
广开言路
广开言路 2021-01-29 01:08

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 nu

相关标签:
1条回答
  • 2021-01-29 02:05

    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.

    0 讨论(0)
提交回复
热议问题