免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2116 | 回复: 0
打印 上一主题 下一主题

Map与HashMap的使用 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-08-01 12:54 |只看该作者 |倒序浏览
Map与HashMap的使用



一、HashMapDemo类用于构建需要放进Map中的对象
  1. package hashmap;

  2. public class HashMapDemo {
  3. private String name;
  4. private String school;

  5. public HashMapDemo(String name,String school){
  6.   this.name=name;
  7.   this.school = school;
  8. }


  9. public String toString(){
  10.   return  school+"毕业的"+name;
  11. }
  12. }
复制代码
二、用于测式HashMap类中的对象
  1. package hashmap;

  2. import java.util.HashMap;
  3. import java.util.Map;

  4. public class HashMapTest {
  5. public static void main(String[] args) {
  6.   HashMapDemo stu1=new HashMapDemo("李明","北京中心");
  7.   HashMapDemo stu2 = new HashMapDemo("刘丽","天津中心");
  8.   
  9.   Map students=new HashMap();
  10.   //把英文名称与学员对象按照"键-值对"的方式存储在HashMap中
  11.   students.put("Jack", stu1);
  12.   students.put("rose", stu2);
  13.   //分别打印键集、值集、以及键-值对集合
  14.   System.out.println("键集:"+students.keySet());
  15.   System.out.println("值集:"+students.values());
  16.   System.out.println("键-值对集合:"+students);
  17.   
  18.   String key="Jack";
  19.   //判断是否存在某个键,如果是同,则根据键获取相应的值
  20.   if(students.containsKey(key)){
  21.    System.out.println(students.get(key));
  22.   }
  23.   
  24.   //根据键删除某个值
  25.   students.remove(key);
  26.   System.out.println(students);
  27.   
  28. }
  29. }
复制代码
总结:


   1、存储数据到HashMap中用Map 对象.put("键",值)。


   2、获取键集使用Map 对象.keySet()方法。


   3、判断是否存在某个键用 Map对象.containsKey(键)方法。


   4、获取某个键所对应的值使用Map 对象.get(键)方法。





5、根据键删除Map对象中某个对象使用Map 对象.remove(键)方法。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP