import java.util.Collection; |
import java.util.HashMap; |
import java.util.Iterator; |
/** |
* @ClassName: HashMapTest |
* @Description: TODO(这里用一句话描述这个类的作用) |
* @author Zhouwei |
* @date 2014-4-3 上午9:10:43 |
* |
*/ |
public class HashMapTest { |
/** |
* @param args |
*/ |
public static void main(String[] args) { |
// TODO Auto-generated method stub |
|
Student zhoutao= new Student( "周涛" , 19 ); |
Student chenwenjie= new Student( "陈文杰" , 20 ); |
Student qiaoxin= new Student( "乔鑫" , 20 ); |
|
|
HashMap map= new HashMap(); |
//键值对 集合 |
|
//添加元素 |
//map.put(key, value); |
|
map.put(zhoutao.getName(), zhoutao); |
map.put(chenwenjie.getName(), chenwenjie); |
map.put(qiaoxin.getName(), qiaoxin); |
|
|
//查找元素, get(key),返回Object 类型的对象,要强转 |
Student s=(Student)map.get( "乔鑫" ); |
System.out.println(s); |
|
//删除元素 remove(key) |
map.remove( "周涛" ); |
|
//遍历map, iterator 迭代器 |
Iterator iter= map.values().iterator(); |
System.out.println( "删除 ,键为 周涛的元素后:" ); |
while (iter.hasNext()){ |
Student obj=(Student)iter.next(); |
System.out.println(obj); |
} |
|
|
|
//values()返回一个集合 |
Collection c_map=map.values(); |
//collection 接口 没有提供 get(下标) |
/*for(int i=0;i<c_map.size();i++){ |
System.out.println(c_map.g); |
}*/ |
|
//for( 元素类型 对象名 :集合) |
for (Object o : c_map){ |
Student stu=(Student)o; |
System.out.println(stu); |
} |
|
} |
} |