zoukankan      html  css  js  c++  java
  • 【JAVA】HashMap入门到放弃:使用HashMap

    摘要:作为HashMap系列学习笔记的开篇,我认为要先熟悉HashMap的使用场景。

    ==========================================================================================

    Map本质上还是属于集合类型的数据结构。

    下面的代码段演示了Map的常用操作(CURD),注意遍历Map尽量使用Entry方式。

     1 HashMap<String, Double> scores = new HashMap<>();
     2 
     3         scores.put("Sam", 100.0);
     4         scores.put("Jacky", 50.0);
     5         scores.put("Tim", 80.0);
     6 
     7         System.out.print(scores);
     8 
     9         scores.put("Tim", 100.0);
    10         System.out.print(scores);
    11         System.out.print(scores.toString());
    12 
    13         System.out.print(scores.get("Sam"));
    14 
    15         System.out.println(scores.containsKey("Sam"));
    16         System.out.println(scores.containsValue(100.0));
    17         
    18         //traverse, cost more time
    19         Iterator<String> it = scores.keySet().iterator();
    20         while(it.hasNext()) {
    21             String tmp = it.next();
    22             System.out.println(tmp);
    23             System.out.println(scores.get(tmp));
    24         }
    25 
    26         System.out.println("count of student:" + scores.size());
    27         System.out.println("scores is " + (scores.isEmpty() ? "empty" : "not empty"));
    28 
    29         //traverse and delete target, cost less
    30         Iterator<Map.Entry<String, Double>> begIt = scores.entrySet().iterator();
    31         for(; begIt.hasNext(); ) {
    32             Map.Entry<String, Double> item = begIt.next();
    33 
    34             if(item.getValue() == 100.0) {
    35                 begIt.remove();
    36             }
    37         }
    38 
    39         System.out.println(scores);
    40 
    41         scores.clear();
    42         System.out.println(scores);

    输出如下:

    {Tim=80.0, Jacky=50.0, Sam=100.0}{Tim=100.0, Jacky=50.0, Sam=100.0}{Tim=100.0, Jacky=50.0, Sam=100.0}100.0true
    true
    Tim
    100.0
    Jacky
    50.0
    Sam
    100.0
    count of student:3
    scores is not empty
    {Jacky=50.0}
    {}

    PS:实际项目中HashMap用的不多,复杂的操作(如key为HashMap)就不做演示了。

  • 相关阅读:
    汇编中的String
    对于C语言可移植性的思考【转】【补充】
    AT&T Mnemonic Conventions(AT&T汇编助记法的规则)
    Macro和Procedure的比较(汇编中的宏与函数)
    File Descriptor和Sys_call number
    #include <sys/types.h>在哪里?
    IIS7 与 WCF 问题总结
    非常不错的WCF入门文章,来自Artech
    WCF 部署问题 小总结 (HTTP 不能注册的解决方法)
    IIS7 aspx出现500.21错误
  • 原文地址:https://www.cnblogs.com/buffalo/p/7892807.html
Copyright © 2011-2022 走看看