浪潮優派培訓java筆記:第9章 類集Collections(容器)



第9章 類集Collections(容器)

9.1 概述

類集,又稱集合類或容器,用來存放對象。

容器:JavaAPI所提供的一系列類的實例,用於在程序中存放對象。

集合類所在的包:java.util

容器API

Set 接口繼承Collection,但不允許重複。

 List 接口繼承Collection,允許重複,並引入位置下標。

 Map 接口不繼承 Collection。

       如何選擇數據結構:

ArrayList讀塊改慢(類似數組)

LinkedList改快讀慢(類似鏈表)

HashSet兩者之間

9.1  Collection接口

  Collection接口:是一組允許重複的對象。

  Collection接口定義了存取一組對象的方法,其子接口Set和List分別定義了存儲方式。

        Set中的數據對象沒有順序且不可以重複;

        List中的數據對象有順序且可以重複;

 Collection接口的方法摘要

 boolean add(Object element)  // 添加元素。

 boolean addAll(Collection c)  //將指定 collection 中的所有元素都添加到此 collection 中。

 void clear() // 移除此collection 中的所有元素。

 boolean contains(Object element)  //如果此 collection 包含指定的元素,則返回 true。

 boolean containsAll(Collectionc) // 如果此 collection 包含指定 collection 中的所有元素,則返回 true。

 boolean equals(Object element)  // 比較此 collection 與指定對象是否相等。

 boolean isEmpty() // 如果此collection 不包含元素,則返回 true。

 Iterator<E> iterator() // 返回在此 collection 的元素上進行迭代的迭代器。

 boolean remove(Object element) // 從此 collection 中移除指定元素的單個實例,如果存在的話。

 boolean removeAll(Collection c) // 移除此 collection 中那些也包含在指定 collection 中的所有元素。

 boolean retainAll(Collection<?> c) //僅保留此 collection 中那些也包含在指定 collection 的元素。

 int size()//返回此 collection 中的元素數。

 Object[] toArray()//返回包含此collection 中所有元素的數組。

<T>T[]  toArray(T[] a) // 返回包含此collection 中所有元素的數組;返回數組的運行時類型與指定數組的運行時類型相同。

【程序示例】:

public class Name {

    private String firstName;

    private String lastName;

    public Name(StringfirstName, String lastName) {

       this.firstName = firstName;

       this.lastName = lastName;

    }

    public StringgetFirstName() {

       return firstName;

    }

    public StringgetLastName() {

       return lastName;

    }

    public String toString(){

       return firstName + " " + lastName;

    }

}

 

import java.util.*;

public class ArrayListDemo {

    public static void main(String[]args) {

       Collection c= new ArrayList();

       c.add("hello");

       c.add(new Name("f1","l1"));

       c.add(100);

       System.out.println(c.size());

       System.out.println(c); //調用toString方法

    }

}

【運行結果】:3

[hello, f1 l1, 100]

9.1.1  List接口

       List接口:(有順序、可重複)

List接口是Collection的子接口,實現List接口的容器類中的元素是有順序,而且可以重複。

List容器中的元素都對應一個整數型的序號記載其在容器中的位置,可以根據序號存取容器中的元素。

實現類:ArrayList和LinkedList

       ArrayList(重點):(類似數組)

【特點】可以添加重複值、可以添加null、元素下標和添加的順序相符合、允許通過下標訪問元素 

【常用方法】add(),addAll(),remove(), get(int), set(int ,Object);

【程序示例】

    public static void main(String[] args) {

       List list = new ArrayList();

       list.add("120");

       list.add(10); // 自動裝箱

       list.add("hello");

       System.out.println("list:" + list);//list:[120, 10,hello]

       List list2 = new ArrayList();

       list2.add("hello");

       list2.add(1);

       System.out.println("list2:" + list2);//list2:[hello,1]

       list.addAll(list2);// 添加一個集合類

       System.out.println("list:" + list);//list:[120, 10,hello, hello, 1]

       list.add(20);//元素下標和添加的順序相符合,所以20會被放在最後

       System.out.println("list:" + list);//list:[120, 10,hello, hello, 1, 20]

       list.remove(0);

       System.out.println("list:" + list);//list:[10,hello, hello, 1, 20]

       /**

        * ArrayList允許通過下標訪問集合元素

        */

       System.out.println("下標爲2的元素:" + list.get(2));//下標爲2的元素:hello

       list.set(1, "world");//把下標爲1的元素設爲"world"

       System.out.println("list:" + list);//list:[10,world, hello, 1, 20]

       Iteratori = list.iterator();

       while (i.hasNext()){

           //Object o =i.next();

           System.out.print(i.next()+" ");

       }

       System.out.println();

       list.add(null);

       System.out.println("list:" + list);

//list:[10, world, hello, 1, 20, null]

}

 

      LinkedList:(類似鏈表)

【特點】:1.添加對列表的頭部和尾部進行操作的方法  2.可以添加null  3.可以添加重複值

【程序示例】

    public static void main(String[] args) {

       List list = new LinkedList();

       list.add("test");

       list.add("ynz");

       list.add(100);

       System.out.println(list);//[test,ynz, 100]

       System.out.println(list.get(1));//ynz

       list.set(2, "java");//把下標爲2的元素設爲"java"

       System.out.println(list);//[test,ynz, java]

 

       LinkedList list2 = new LinkedList();

       list2.add("hello");

       list2.add(20);

       list2.addFirst("first");//在開頭位置加入"first"

       list2.addLast("last");//在開頭位置加入"last"

       System.out.println(list2);//[first,hello, 20, last]

 

       list.addAll(list2);

       System.out.println(list);//[test,ynz, java, first, hello, 20, last]

 

       list2.removeFirst();//刪除第一個元素

       list2.removeLast();//刪除第一個元素

       System.out.println(list2);//[hello,20]

 

       // peek():返回集合中第一個元素,且不刪除

       System.out.println(list2.peek());//hello

       System.out.println(list2);//[hello,20]

 

       // poll():返回集合中第一個元素,且刪除此元素

       System.out.println(list2.poll());//hello

       System.out.println(list2);//[20]

 

       list2.add(null);

       list2.add(20);

       System.out.println(list2);//[20,null, 20]

}

9.1.2  Set接口

       Set接口:(有順序、不可以重複)

Set接口是Collection的子接口,Set接口沒有提供額外的方法,但實現Set接口的容器類中的元素是沒有順序的,而且不可以重複。

 實現類:HashSet和TreeSet

       HashSet:

【特點】1.可以添加null 2.不允許重複的元素  

【常用方法】add(),addAll(), iterator(), remove(),contains()

【程序示例】

    public static void main(String[] args) {

       Set set1 = new HashSet();

       set1.add(100);

       set1.add("hello");

       set1.add(3.5);

       System.out.println("set1:" + set1);// set1:[100,hello, 3.5]

       set1.add("hello"); // 相同的元素不會被加入

       set1.add(null);

       System.out.println("set1:" + set1);// set1:[100,hello, 3.5, null]

       Set set2 = new HashSet();

       set2.add(1);

       set2.add("hello");

       System.out.println("set2:" + set2);// set2:[hello,1]

       set1.addAll(set2); // 添加一個集合類

       System.out.println("set1:" + set1);// set1:[100,hello, 1, 3.5, null]

       set1.remove(3.5); // 刪除某個元素

       System.out.println("set1:" + set1);// set1:[100,hello, 1, null]

       set1.removeAll(set2); // 刪除一個集合類

       System.out.println("set1:" + set1);// set1:[100,null]

       /**

        * 通過迭代器來遍歷Set

        */   

       Iterator i = set1.iterator(); // 創建迭代器

       System.out.print("set1的元素:");

       while (i.hasNext()) {

           System.out.print(i.next() + " ");

       }

       System.out.println();

       boolean bool = set1.contains(100);

       System.out.println(bool);// true

       set1.clear(); // 刪除集合類的所有元素

       System.out.println("set1:" + set1);//set1:[]

    }

 

      TreeSet:

【特點】1.不允許重複值 2.可以對元素進行排序(升序),元素類型要一致 3.不允許添加null值

【程序示例】

    public static void main(String[] args) {

       Set set = new TreeSet();

       set.add(100);

       set.add(120);

       System.out.println(set);//[100,120]

       TreeSet set2 = new TreeSet();

       set2.add(10);

       set2.add(120);

       set.addAll(set2);

       System.out.println(set);//[10,100, 120]

       set.add(5);

       System.out.println(set);//[5, 10,100, 120]

       set.add(20);

       System.out.println(set);//[5, 10,20, 100, 120]

       // set.add(null); 不能添加null

       Iterator i = set.iterator();

       while (i.hasNext()) {

           System.out.print(i.next()+"");

       }

       System.out.println();

       System.out.println("set中元素的個數:" + set.size());//set中元素的個數:5

    }

 

歷史類(JDK1.0)(瞭解)

ArrayList:Vector

LinkedList:Stack

 

9.2  Map接口

      Map接口

Map接口定義了存儲“鍵(key)-值(value)映射對”的方法。

Map中存放的是key=value對(鍵-值對),可以通過鍵尋找值。(key和value之間用=連接)

Map類中存儲的鍵-值對通過鍵(key)來標識,所以key不能重複,但值可以重複。

實現類:HashMap和TreeMap

       HashMap :(重點)由哈希表實現

1.存放鍵值對 2.鍵不能重複,值可以重複  3.鍵和值都可以爲null

遍歷map的兩種方式:

(1)通過keySet()獲取所有的鍵,通過鍵取值:get(key)

(2)通過entrySet()獲取所有的Map.Entry<K,V>類型的數據,通過每個Map.Entry的getKey,getValue方法來獲取鍵和值

【程序示例】

    public static void main(String[] args) {

       Map map = new HashMap();

       map.put(1, 2000);

       map.put(2, 4000);

       map.put(3, 2500);

       map.put("java", "1578");

       map.put(4, "good");

       System.out.println(map);//{java=1578,2=4000, 4=good,1=2000, 3=2500}

       map.put(2, 5000);  //會覆蓋原有的value,因爲key不可以重複

       System.out.println(map);//{java=1578,2=5000, 4=good,1=2000, 3=2500}

       map.put(5, 2000);  // value可以重複

       System.out.println(map);

//{java=1578, 2=5000, 4=good, 1=2000, 3=2500, 5=2000}

       map.put(null, null); //可以添加null

       System.out.println(map);

//{java=1578, 2=5000, 4=good, 1=2000, null=null, 3=2500,5=2000}

       /*

        * 通過key找value的方法: value get(key);遍歷map

        */

       Set keys = map.keySet();// keySet():返回map中所有鍵的集合

       Iterator i = keys.iterator();

       while (i.hasNext()) {

           Object key = i.next();

           System.out.println("value:" + map.get(key));

       }

【遍歷map的兩種方法】

    public static void main(String[] args) {

       Map<Integer, String> map = new HashMap<Integer, String>();

       map.put(1, "world");

       map.put(2, "String");

       map.put(3, "hello");

       /**

        * 遍歷map的方法(一) keySet(); 找到所有的鍵

        */

       Set<Integer> set = map.keySet();

       Iterator<Integer> i = set.iterator();

       while (i.hasNext()) {

           Integer key = i.next();

           System.out.println(map.get(key));

       }

       /*

        * 遍歷map的方法(二)Set<Map.Entry<k,V>> entrySet()

        *                                   返回此映射中包含的映射關係的 set 視圖。

        */

       Set<Map.Entry<Integer, String>> set2 =map.entrySet();

       //Iterator<Map.Entry<Integer, String>> i2=set2.iterator();也可實現

       for (Map.Entry<Integer, String> entry : set2) {

           Integer key = entry.getKey();

           String value = entry.getValue();

           System.out.println(key + " =" + value);

       }

    }

      TreeMap:由二叉樹實現

1.存放鍵值對 2.鍵不能重複,值可以重複 3.按鍵的大小進行自動排序(升序) 4.鍵不能爲null,值可以爲null

【程序示例】

    public static void main(String[] args) {     

       Map<String,String> map=new TreeMap<String,String>();   

       map.put("001", "lilei");

       map.put("002", "hanmeimei");

       map.put("hello", "nihao");

       map.put("good", "morning");

       map.put("aaa", "test");    

       map.put("good", "test");

       map.put("003",null);

       System.out.println(map);

//{001=lilei, 002=hanmeimei, 003=null, aaa=test,good=test, hello=nihao}

}

 

歷史集合類:(瞭解)

HashMap:HashTable

TreeMap:Properties

 

9.3  Iterator接口

       Iterator接口: (重點)

主要用於遍歷集合類中的元素;

所有實現了Collection接口的容器類都有一個iterator()方法用以返回一個實現了Iterator接口的對象。

Iterator對象稱作迭代器,用以方便的實現對容器內元素的遍歷操作。

Iterator接口定義瞭如下方法:

        boolean  hasNext(); //判斷容器內是否還有元素

        Object  next(); //返回容器內的下一個元素

        void  remove(); //


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章