zoukankan      html  css  js  c++  java
  • 吴裕雄--天生自然 JAVA开发学习:集合框架

    import java.util.*;
     
    public class Test{
     public static void main(String[] args) {
         List<String> list=new ArrayList<String>();
         list.add("Hello");
         list.add("World");
         list.add("HAHAHAHA");
         //第一种遍历方法使用foreach遍历List
         for (String str : list) {            //也可以改写for(int i=0;i<list.size();i++)这种形式
            System.out.println(str);
         }
     
         //第二种遍历,把链表变为数组相关的内容进行遍历
         String[] strArray=new String[list.size()];
         list.toArray(strArray);
         for(int i=0;i<strArray.length;i++) //这里也可以改写为  foreach(String str:strArray)这种形式
         {
            System.out.println(strArray[i]);
         }
         
        //第三种遍历 使用迭代器进行相关遍历
         
         Iterator<String> ite=list.iterator();
         while(ite.hasNext())//判断下一个元素之后有值
         {
             System.out.println(ite.next());
         }
     }
    }
    import java.util.*;
     
    public class Test{
         public static void main(String[] args) {
          Map<String, String> map = new HashMap<String, String>();
          map.put("1", "value1");
          map.put("2", "value2");
          map.put("3", "value3");
          
          //第一种:普遍使用,二次取值
          System.out.println("通过Map.keySet遍历key和value:");
          for (String key : map.keySet()) {
           System.out.println("key= "+ key + " and value= " + map.get(key));
          }
          
          //第二种
          System.out.println("通过Map.entrySet使用iterator遍历key和value:");
          Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
          while (it.hasNext()) {
           Map.Entry<String, String> entry = it.next();
           System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
          }
          
          //第三种:推荐,尤其是容量大时
          System.out.println("通过Map.entrySet遍历key和value");
          for (Map.Entry<String, String> entry : map.entrySet()) {
           System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
          }
        
          //第四种
          System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
          for (String v : map.values()) {
           System.out.println("value= " + v);
          }
         }
    }
  • 相关阅读:
    CodeForces 659F Polycarp and Hay
    CodeForces 713C Sonya and Problem Wihtout a Legend
    CodeForces 712D Memory and Scores
    CodeForces 689E Mike and Geometry Problem
    CodeForces 675D Tree Construction
    CodeForces 671A Recycling Bottles
    CodeForces 667C Reberland Linguistics
    CodeForces 672D Robin Hood
    CodeForces 675E Trains and Statistic
    CodeForces 676D Theseus and labyrinth
  • 原文地址:https://www.cnblogs.com/tszr/p/10967050.html
Copyright © 2011-2022 走看看