Here you can find the source of toString(Map
public static <K, V> String toString(Map<K, V> map)
//package com.java2s; //License from project: Apache License import java.util.Map; public class Main { public static <K, V> String toString(Map<K, V> map) { StringBuilder sb = new StringBuilder(); sb.append("["); boolean first = true; for (Map.Entry<K, V> entry : map.entrySet()) { if (first) { first = false;/* w w w . j a va2 s .c om*/ } else { sb.append(","); } sb.append(" "); if (entry.getKey() == map || entry.getValue() == map) { // don't overflow stack if map contains itself safeToString(sb, entry.getKey(), entry, "( this entry )", map, "( this map )"); sb.append(" => "); safeToString(sb, entry.getValue(), entry, "( this entry )", map, "( this map )"); } else { sb.append(entry); } } sb.append(" ]"); return sb.toString(); } public static String toString(Map.Entry<?, ?> entry) { StringBuilder sb = new StringBuilder(); safeToString(sb, entry.getKey(), entry, "( this entry )"); sb.append(" => "); safeToString(sb, entry.getValue(), entry, "( this entry )"); return sb.toString(); } private static void safeToString(StringBuilder sb, Object o, Object current1, String substitute1, Object current2, String substitute2) { if (o == current1) { sb.append(substitute1); } else if (o == current2) { sb.append(substitute2); } else { sb.append(o); } } private static void safeToString(StringBuilder sb, Object o, Object current, String substitute) { if (o == current) { sb.append(substitute); } else { sb.append(o); } } }