代码如下
主类
package edu.wit.kelvin.demo;
import java.util.Iterator;
import java.util.Map ;
import java.util.HashMap ;
import java.util.TreeMap ;
public class MyTestCollection2 {
public static void main(String[] args){
Person p1 = new Person("yang" , 12121) ;
Person p2 = new Person("su" , 12122);
Person p3 = new Person("chg" , 12123) ;
Person p4 = new Person("peng" , 12124) ;
Person p5 = new Person("cai" , 12125) ;
Person p6 = new Person("kelvin" , 12126) ;
System.out.println("**********start*********");
System.out.println("a implement of Map with HashMap");
Map<Integer , Person> hashMap = new HashMap<Integer , Person>() ;
hashMap.put(p1.getId_card(), p1) ;
hashMap.put(p2.getId_card(), p2) ;
hashMap.put(p3.getId_card(), p3) ;
hashMap.put(p4.getId_card(), p4) ;
hashMap.put(p5.getId_card(), p5) ;
hashMap.put(p6.getId_card(), p6) ;
Person tmp = new Person() ;
for(Iterator<Integer> it = hashMap.keySet().iterator(); it.hasNext();){
tmp = hashMap.get(it.next()) ;
System.out.println(tmp.getId_card()+":"+tmp.getName());
}
System.out.println("a implement of Map with TreeMap");
Map<Integer , Person> treeMap = new TreeMap<Integer , Person>() ;
// 使用treeMap集合中元素对象的属性作为key
treeMap.put(p1.getId_card(), p1) ;
treeMap.put(p2.getId_card(), p2) ;
treeMap.put(p3.getId_card(), p3) ;
treeMap.put(p4.getId_card(), p4) ;
treeMap.put(p5.getId_card(), p5) ;
treeMap.put(p6.getId_card(), p6) ;
for(Iterator<Integer> it = treeMap.keySet().iterator(); it.hasNext();){
tmp = treeMap.get(it.next() ) ;
System.out.println(tmp.getId_card()+":"+tmp.getName());
}
System.out.println("a implement of Map with HashMap with specified key");
Map<Integer , Person> hashMap2 = new HashMap<Integer , Person>() ;
// 使用自定义的key序列
Integer[] id = new Integer[]{1 ,2 ,3, 4,5 , 6} ;
hashMap2.put(id[0], p1) ;
hashMap2.put(id[1], p2) ;
hashMap2.put(id[2], p3) ;
hashMap2.put(id[3], p4) ;
hashMap2.put(id[4], p5) ;
hashMap2.put(id[5], p6) ;
for(Iterator<Integer> it = hashMap2.keySet().iterator();it.hasNext();)
{
if(0 == 0){
Person tmp1 = new Person() ;
Integer index = it.next();
tmp1 = hashMap2.get(index);
System.out.println(index.toString()+":"+tmp1.getName());
}else{
// Iterator的next()方法,先获取当前对象,然后在将指针指向下一对象。
System.out.println(it.next().toString()+":"+hashMap2.get(it.next()).getName()) ;
}
}
}
}
红色代码出为重点,是对next()方法的理解。
package edu.wit.kelvin.demo;
public class Person {
private String name;
private Integer idCard ;
// private Number idCard ;
Person(){
}
Person(String name , int id){
this.name = name ;
this.idCard = id ;
}
// public Number getId_card(){
public Integer getId_card(){
return this.idCard ;
}
public String getName(){
return this.name ;
}
}
运行结果如下
**********start*********
a implement of Map with HashMap
12121:yang
12123:chg
12122:su
12125:cai
12124:peng
12126:kelvin
a implement of Map with TreeMap
12121:yang
12122:su
12123:chg
12124:peng
12125:cai
12126:kelvin
a implement of Map with HashMap with specified key
1:yang
2:su
3:chg
4:peng
5:cai
6:kelvin