为什么打印Java集合对象打印出来的是存储的值,而不是哈希值

Collection(接口)---AbstractCollection(抽象类)--AbstractList(抽象类)--ArrayList(类)

Collection(接口)---AbstractCollection(抽象类)--AbstractSet(抽象类)--TreeSet(类)

Map(接口)--AbstractMap(抽象类)--HashMap(类)

在AbstractCollection中实现了toString方法。

public String toString() {

        Iterator<E> it = iterator();

        if (! it.hasNext())

            return "[]";

        StringBuilder sb = new StringBuilder();

        sb.append('[');

        for (;;) {

            E e = it.next();

            sb.append(e == this ? "(this Collection)" : e);

            if (! it.hasNext())

                return sb.append(']').toString();

            sb.append(',').append(' ');

        }

在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(',').append(' ');

        }

Student student=new Student();

System.out.println(student);此时输出的为哈希值。因为未重写toString方法。

Object类的toString方法返回的是

public String toString() {

        return getClass().getName() + "@" + Integer.toHexString(hashCode());

    }

总的来说,是因为AbstractCollection和AbstractMap实现了

猜你喜欢

转载自blog.csdn.net/shilu963/article/details/81200520