继承HashMap类,重写了toString()方法。,hashmaptostring
继承HashMap类,重写了toString()方法。,hashmaptostring
package collections_example;
import java.util.*;
/**
*
* @author andy
*/
//定义Person类
class Person{
private String name;
private int age;
Person(String name, int age){
this.name=name;
this.age=age;
}
//重写Person类的toString()方法
@Override
public String toString(){
return "[name="+this.name+",age="+this.age+"]";
}
}
//定义一个HashMapSon类,它继承HashMap类
class HashMapSon<K,V> extends HashMap {
//重写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()+",");
buffer.append("值为"+value.toString()+"/n");
if(!i.hasNext())
return buffer.toString();
}
}
}
//以下为原来写的toString()方法,存在编译问题。
/*
public String toString(){
Set keyset = this.keySet();
Iterator ir = keyset.iterator();
StringBuffer temps=null;
String s=null;
System.out.println("输出HashMap中的元素:");
while(ir.hasNext()){
//System.out.println(ir.next().toString());
K key = (K)ir.next();
V value = (V)this.get(ir.next());
temps= temps.append(key.toString()+" "+value.toString());
}
s = new String(temps);
return s;
}
*/
//主类
public class HashMap_Sample1 {
public static void main(String[] args){
HashMapSon<Integer,Person> hm = new HashMapSon<Integer,Person>();
hm.put(1003,new Person("tom",21));
hm.put(1001,new Person("keith",32));
hm.put(1002,new Person("jack",24));
hm.put(1000,new Person("jerry",21));
System.out.println(hm);
}
}
运行结果如下:
键为1001,值为[name=keith,age=32]
键为1000,值为[name=jerry,age=21]
键为1003,值为[name=tom,age=21]
键为1002,值为[name=jack,age=24]
说明如下:
HashMap类的toString()方法继承自java.util.AbstractMap,方法说明如下:
public String toString()
- 返回此映射的字符串表示形式。该字符串表示形式由键-值映射关系列表组成,按照该映射 entrySet 视图的迭代器返回的顺序排列,并用括号 ("{}") 括起来。相邻的映射关系是用字符 ", "(逗号加空格)分隔的。每个键-值映射关系按以下方式呈现:键,后面是一个等号 ("="),再后面是关联的值。键和值都通过
String.valueOf(Object)
转换为字符串。
源代码如下:
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(", ");
}
}
其中,Entry<K,V>是Map接口的内部静态接口。
public static interface Map.Entry<K,V>
映射项(键-值对)。Map.entrySet 方法返回映射的 collection 视图,其中的元素属于此类。获得映射项引用的唯一 方法是通过此 collection 视图的迭代器来实现。这些 Map.Entry 对象仅 在迭代期间有效;更确切地讲,如果在迭代器返回项之后修改了底层映射,则某些映射项的行为是不确定的,除了通过 setValue 在映射项上执行操作之外。
所以 Iterator<Entry<K,V>> i = entrySet().iterator(); 获得了Entry<K,V>的引用i。
相关文章
- 暂无相关文章
用户点评