java各种toString步骤
java各种toString方法
- java的根类: Object
/* getClass().getName() + '@' + Integer.toHexString(hashCode()) * </pre></blockquote> * * @return a string representation of the object. */ public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
所以我们见到的没有override toString()方法的都会调用Object的toString()方法。 - 数组:
/** * [I@119298d */ int[] a = {1,2,3}; System.out.println(a.toString()); /** * [[I@119298d */ int[][] b = {{1},{2},{3}}; System.out.println(b.toString());
无法override 数组类的toString()方法,它是由虚拟机在第一次遇到时生成的数组数据类型. - String类型
/** * This object (which is already a string!) is itself returned. * * @return the string itself. */ public String toString() { return this; }
- Set和List
/** * [1, 1, 1, 1] * [1] */ List list = new ArrayList(Collections.nCopies(4, 1)); System.out.println(list.toString()); Set set = new TreeSet(Collections.nCopies(4, 1)); System.out.println(set.toString());
这个是由抽象类AbstractCollection实现的toString()方法:public String toString() { Iterator<E> i = iterator(); if (! i.hasNext()) return "[]"; StringBuilder sb = new StringBuilder(); sb.append('['); for (;;) { E e = i.next(); sb.append(e == this ? "(this Collection)" : e); if (! i.hasNext()) return sb.append(']').toString(); sb.append(", "); } }
- Map
/** * {} */ Map map = new HashMap(); System.out.println(map.toString());
这个是由抽象类AbstractMap实现的toString()方法:public String toString() { Iterator<Entry<K,V>> i = entrySet().iterator(); if (! i.hasNext()) return "{}"; StringBuilder sb = new StringBuilder(); sb.append('{'); for (;;) { Entry<K,V> e = i.next(); K key = e.getKey(); V value = e.getValue(); sb.append(key == this ? "(this Map)" : key); sb.append('='); sb.append(value == this ? "(this Map)" : value); if (! i.hasNext()) return sb.append('}').toString(); sb.append(", "); } }
应该还有比较特殊的,以后慢慢补充,现在只想到这些。