集合的遍歷

這裏寫圖片描述

集合的長度是可變的:
1.Collection 接口:子類接口分別是List和Set
List:常用的實類,ArrayList ,LinkedList.
ArrayList:是基於數組,特點是查詢快,增刪慢,效率高安全性低。
LinkedList:是基於鏈表,增刪快,查詢慢。
Vector:也是基於數組,和ArrayList的區別,安全性高,效率低
2.Map得子類:鍵值對遍歷
HashMap
LinkedHashMap

`list的遍歷:
public class MyLinkedList {
    List<Shape> list; 

    public void genDate(){
        list=new LinkedList<Shape>();
        list.add(new DrawLine(1,1,1,1,1));
        list.add(new DrawLine(2,1,1,1,1));
        list.add(new DrawLine(3,1,1,1,1));
        list.add(new DrawLine(4,1,1,1,1));
        list.add(new DrawLine(5,1,1,1,1));

    }

    public void printDate() {
      for(int i=0;i<list.size();i++){
          System.out.println(list.get(i));
      }
    }
}

Map遍歷:public class MyMap {

public class MyMap {

    Map<Integer,Shape> myMap = new HashMap<Integer,Shape>();;

    public void genDate() {
        myMap.put(1, new DrawLine(1, 1, 1, 1, 1));
        myMap.put(2, new DrawLine(2, 1, 1, 1, 1));
        myMap.put(3, new DrawLine(3, 1, 1, 1, 1));
        myMap.put(4, new DrawLine(4, 1, 1, 1, 1));
    }

    public void printDate() {
        Set<Integer> set = myMap.keySet();
        Iterator<Integer> it = set.iterator();
        while(it.hasNext()){
            int key = it.next();
            System.out.println(myMap.get(key));
        }
    }
}

Map遍歷的第二種方法效率更高

HashMap<String, Shape> hashMap = new HashMap<String, Shape>();

        hashMap.put("shape1", new DrawLine(1, 1, 1, 1, null, 1));
        hashMap.put("shape2", new DrawLine(2, 1, 1, 1, null, 1));
        hashMap.put("shape3", new DrawLine(3, 1, 1, 1, null, 1));
        hashMap.put("shape4", new DrawLine(4, 1, 1, 1, null, 1));
        hashMap.get("shape1");
        Set<Entry<String,Shape>> set = hashMap.entrySet();
        Iterator<Entry<String ,Shape>> it = set.iterator();
        while(it.hasNext()){
            Entry<String,Shape> en = (Entry<String,Shape>)it.next();
            String key = en.getKey();
            String value = en.getValue();
            System.out.println(key+"======"+value);
        }
發佈了31 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章