不要依赖于该方法,toString()
因为它是一个可以从一个Java版本更改为另一个版本的实现细节,您应该实现自己的方法.
假设您使用Java 8,它可能是:
public static <K, V> String mapToString(Map<K, V> map) {
return map.entrySet()
.stream()
.map(entry -> entry.getKey() + ":" + entry.getValue())
.collect(Collectors.joining(", ", "{", "}"));
}
Run Code Online (Sandbox Code Playgroud)
如果你想拥有完全相同的实施为AbstractMap#toString()
来检查,如果该键或值是当前地图,代码则是:
public static <K, V> String mapToString(Map<K, V> map) {
return map.entrySet()
.stream()
.map(
entry -> (entry.getKey() == map ? "(this Map)" : entry.getKey())
+ ":"
+ (entry.getValue() == map ? "(this Map)" : entry.getValue()))
.collect(Collectors.joining(", ", "{", "}"));
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2246 次 |
最近记录: |