重写HashMap的toString()方法,hashmaptostring
分享于 点击 37805 次 点评:133
重写HashMap的toString()方法,hashmaptostring
写在前面
今天本人在写java程序的时候,需要用到HashMap,先将数据加入到HashMap中,然后使用toString()方法,打印出HashMap中存储的所有数据。然而,HashMap原始的toString()方法并不能满足本人输出格式的需要,故本人决定重写HashMap的toString()方法。闲话不多说,直接看代码。
HashMap的toString()方法源码
下面,我们看看HashMap的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(' ');
}
}
本人重点关注的是它的输出格式。其输出格式为:
{key1=value1,key2=value2,… key n=value n}
*注意,输出时key1,key2 … key n的顺序和输入的顺序并不相同。
我们可以通过一下测试程序查看结果:
import java.util.HashMap;
public class test {
public static void main(String[] args) {
HashMap<String,Integer> map = new HashMap<String,Integer>();
map.put("分享", 23);
map.put("微博", 20);
map.put("预测", 55);
map.put("爱心",12);
System.out.println(map.toString());
}
}
其输出结果为:
{分享=23, 爱心=12, 预测=55, 微博=20}
本人想得到的输出格式为:
分享 23
爱心 12
预测 55
微博 20
故重写toString()方法。
重写toString()方法
这里,本人新建了一个类myHashMap,它继承HashMap,让后在没有HashMap中重写toString()方法。代码如下:
import java.util.*;
//定义一个HashMapSon类,它继承HashMap类
class myHashMap<K, V> extends HashMap<K,V> {
private static final long serialVersionUID = -5894887960346129860L;
// 重写HashMapSon类的toString()方法
@Override
public String toString() {
Set<Map.Entry<K, V>> keyset = this.entrySet();
Iterator<Map.Entry<K, V>> i = keyset.iterator();
if (!i.hasNext())
return "";
StringBuffer buffer = new StringBuffer();
// buffer.append("{");//注意此程序与源代码的区别
for (;;) {
Map.Entry<K, V> me = i.next();
K key = me.getKey();
V value = me.getValue();
buffer.append(key.toString() + "\t");
buffer.append(value.toString() + "\n");
if (!i.hasNext())
return buffer.toString();
}
}
}
然后再main中,将:
HashMap<String,Integer> map = new HashMap<String,Integer>();
改为:
myHashMap<String,Integer> map = new myHashMap<String,Integer>();
在执行程序,我们会看到输出结果如下:
分享 23
爱心 12
预测 55
微博 20
bingo!就是这么简单。HashMap的toString()方法重写完成。读者可以根据自己的需求来重写HashMap的toString()方法。Just like this。
相关文章
- 暂无相关文章
用户点评