package com.tn.hashMap;

 public class Student {
private String id;
private String name;
public Student(String id, String name) {
super();
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}

Student

 package com.tn.hashMap;

 import java.util.HashMap;
import java.util.Map;
import java.util.Set; public class HashMapDemo {
public static void main(String[] args){
Student student1=new Student("0001","哪吒");
Student student2=new Student("0002","杨戬");
Student student3=new Student("0003","雷震子");
HashMap<String,Student> hm=new HashMap<String,Student>();
//HashMap的键值对都是Object类型,如果需要用到基本类型可用Integer之类的包装类
hm.put(student1.getId(), student1);
hm.put(student2.getId(), student2);
hm.put(student3.getId(), student3);
//put方法如果key相同,则后面的value会覆盖前面的
System.out.println(hm.size());
System.out.println(hm); //通过keySet方法用Set遍历
Set<String> set=hm.keySet();
for(String str:set){
System.out.println(hm.get(str));//打印出来的顺序是不可预知的
} //通过entrySet方法用set遍历
/*放入HashMap集合中的key、Value会被包装成Map.Entry内部类的属性
* 一个键值对成为一个Map.Entry实例对象
*
*/
Set<Map.Entry<String, Student>> set1=hm.entrySet();
//Set<Map<K,V>.Entry<K, V>> 注:Map后的泛型可不指明,不用写。
for(Map.Entry<String, Student> mEntry:set1){
System.out.println(mEntry.getKey()+":"+mEntry.getValue());
}
}
}

HashMapDemo


通过HashMap计算字符串中各字母出现次数:

 String str="abbcccddddeeeeeffffff";
HashMap<String,Integer> hashMap=new HashMap<String,Integer>();
for(int i=0;i<str.length();i++){
if(!hashMap.containsKey(str.substring(i, i+1))){
hashMap.put(str.substring(i, i+1), 1);
}else{
hashMap.put(str.substring(i,i+1), hashMap.get(str.substring(i, i+1))+1);
}
}
System.out.println(hashMap);

snippet

最新文章

  1. XML Schema and XMLspy notes
  2. Topcoder SRM570 900 CurvyonRails
  3. JS-Dom概念
  4. OC之0801
  5. [转] 国内外最全面和主流的JS框架与WEB UI库(强烈推荐)
  6. JavaScript 同源策略
  7. 经常被忽略的几个CSS3属性之强大应用(一、timing-function: steps() 二、animation-direction  三、timing-function: cubic-bezier())
  8. APK签名校验绕过
  9. c语言全局变量与局部变量(当变量重名时)的使用情况
  10. &lt;微信应用开发系列&gt;定时刷新AccessToken
  11. ubuntu12.04安装openjdk-7
  12. SpringBoot 整合 Swagger2
  13. 《Spring Cloud与Docker微服务架构实战》配套代码
  14. C#中关键字 &#39;User&#39; 附近有语法错误
  15. mysq带条件的分页查询数据结果错误
  16. 20175224 2018-2019-2 《Java程序设计》第七周学习总结
  17. asp.net core2.0中网站发布的时候,怎么样才配置才可以使视图文件不被打包进去?
  18. java基础篇---HTTP协议
  19. 2018.12.30 poj3734 Blocks(生成函数)
  20. mormot中间件成功匹配客户端FDMemTable和ClientDataSet

热门文章

  1. jmockit学习
  2. Winwos Server 2012发布ASP.NET MVC5 项目
  3. Next week plan
  4. 读Kafka Consumer源码
  5. Tinc VPN
  6. 基于ESXI6.5的服务器基本配置(HP DL388 Gen 9)
  7. 作为新手,SEO要避免的五大误区
  8. Springmvc ModelAndView踩过的坑之HttpServletResponse response
  9. 智能合约语言Solidity教程系列2 - 地址类型介绍
  10. appium测试准备记录