Java基礎:集合

源代碼下載:http://download.csdn.net/detail/zhoujing_0424/9239347
一. 集合概述
1. 集合類的由來
對象用於封裝特有數據,對象多了就需要進行存儲,如果對象的個數不確定,那麼就用集合容器進行存儲。集合是用於存儲對象的容器。
2. 集合的概念
集合有時又稱爲容器,簡單地說,它是一個對象,能將具有相同性質的多個元素匯聚成一個整體。集合被用於存儲、獲取、操縱和傳輸聚合的數據。
3. 集合與數組的區別
1)集合長度是可變的;數組長度固定的。
2)集合中只能存儲對象;數組中既可以存儲對象,又可以存儲基本類型數據。
3)集合中存儲的對象可以是任意類型的;數組中只能存儲同一類型的對象。

二. 集合框架
集合容器因爲內部結構不同,有很多具體的容器,不斷的向上抽取,就形成了集合框架。
Java集合框架圖
Java平臺提供了一個全新的集合框架,框架的核心爲Collection、List(列表)、Set(集合)和Map(映射),如上圖所示。圖中虛線框的爲接口,實線框的爲具體的實現類。集合類的框架爲集合的實現者提供了大量的接口和抽象類,並對其中的某些機制給予了描述,例如,Iterator(迭代協議)。實現Comparable接口或Comparator接口,用戶可以根據需要對集合中的元素進行排序。爲了方便用戶使用,Java平臺還提供了Collections和Arrays兩個靜態工具類。下面就從集合框架中的兩個基本的接口Collection和Map入手,對其分別進行深入說明。

三. Collection接口
Collection是集合繼承樹中最頂層的接口,幾乎所有的Java集合框架成員都繼承實現了Collection接口,或者與其有密切關係。Collection提供了關於集合的通用操作。Collection的常見方法:
1.添加
add(Object obj);
addAll(Collection c);
2.刪除
remove(Object obj);
removeAll(Collection c);
void clear();
3.判斷
boolean contains(Object obj);
boolean containsAll(Collection c);
boolean isEmpty();
4.獲取
int size();
Iterator iterator();
//返回在此collection的元素上進行迭代的迭代器。該對象必須依賴於具體的容器,因爲每一個容器的數據結構都不同,所以該迭代器對象是在容器中進行內部實現的。對於容器的使用者而言,具體的實現並不重要,只要通過容器獲取到該實現的迭代器對象即可,也就是Iterator()方法。Iterator接口就是對所有的collection容器進行元素取出的公共接口。迭代器就是實現了Iterator接口的每一個容器內部的內部對象,Iterator降低容器和取出元素之間的耦合性。
5.其他
boolean retainAll(Collection c);//僅保留此 collection 中那些也包含在指定 collection 的元素
Object[] toArray();//返回包含此collection中所有元素的數組

List和Set接口都實現了Collection接口,兩者的區別如下:
1)List:有序(存入和取出的順序一致),元素都有索引(角標),元素允許重複。
2)Set:元素不能重複,無序。
下面分別對這兩個接口進行演示講解。

四. List接口(列表)

1.List特有的常見方法
List列表作爲集合的一種,其主要特點在於其中的元素保持一定的順序。List特有的常見方法:
(1)添加
void add(int index,E element); //在列表指定位置插入指定元素
void add(int index,Collection c);//將指定collection中的所有元素插入到列表的指定位置
(2)刪除
E remove(int index);//刪除列表中指定位置的元素
(3)修改
E set(int index,E element);//用指定元素替換列表中指定位置的元素
(4)獲取
E get(int index);//獲取列表指定位置的元素
int indexOf(Object o);//返回列表中指定元素第一次出現的索引,若沒有則返回-1
int lastIndexOf(Object o);//返回列表中指定元素最後一次出現的索引,若沒有則返回-1
List subList(int fromIndex,int toIndex);//返回列表中指定的 fromIndex(包括 )和 toIndex(不包括)之間的部分視圖
ListIterator listIterator();//返回此列表中元素的列表迭代器,可以實現在迭代過程中對元素進行增刪改查。ListIterator是列表迭代器,允許程序員按任一方向遍歷列表、在迭代期間修改列表,並獲得迭代器在當前列表中的位置
ListIterator listIterator(int index);//返回此列表中元素的列表迭代器,從指定位置開始

2.List常用的具體實現類
(1)Vector:內部是數組數據結構,是同步的,效率低,幾乎不用。增刪查詢都很慢。
(2)ArrayList:內部是數組數據結構,是不同步的,效率高,替代了Vector。若需要線程安全則加鎖,而不使用Vector。查詢的速度快。
(3)LinkedList:內部是鏈表數據結構,是不同步的。增刪元素的速度非常快。

package com.zj.list.demo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class ListDemo {

    public static void main(String[] args) {
        List<String> list =new ArrayList<String>();
//      show(list);
        show2(list);
    }

    public static void show(List<String> list){
        list.add("abc1");
        list.add("abc2");
        list.add("abc3");
        System.out.println(list);

//      //插入元素
//      list.add(1, "abc5");
//      
//      //刪除元素
//      list.remove(2);

//      //修改元素
//      list.set(1, "abc6");

        //獲取元素
        System.out.println(list.get(2));

        //獲取子列表
        System.out.println(list.subList(1, 2));//包含1位置的元素,不包含2位置的元素

        System.out.println(list);

    }

    public static void show2(List<String> list){
        list.add("abc1");
        list.add("abc2");
        list.add("abc3");

        /*for(Iterator it=list.iterator();it.hasNext();){
            System.out.println("next:"+it.next());
            Object obj=it.next();
            if(obj.equals("abc2")){
                // 拋出java.util.ConcurrentModificationException
                //集合和迭代器同時操作元素,會導致迭代出問題,則拋出異常
                //解決方法爲:迭代的時候不集合,集合的時候不迭代
                list.add("abc7");
            }
            else{
                System.out.println("next"+obj);
            }
        }*/

        //可以使用Iterator的子接口ListIterator來完成在迭代中對元素進行更多的操作
        //它可以實現在迭代過程中對元素的增刪改查。注意:只有list集合具備該迭代功能。
        for(ListIterator<String> it=list.listIterator();it.hasNext();){
            Object obj=it.next();
            if(obj.equals("abc2")){
                it.add("abc7");
            }
        }

        //list特有的取出方式
        for(int index=0;index<list.size();index++){
            System.out.println("get:"+list.get(index));
        }   
    }
}
package com.zj.list.demo;

import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;

public class VectorDemo {

    public static void main(String[] args){
        Vector<String> v=new Vector<String>();
        v.addElement("abc1");
        v.addElement("abc2");
        v.addElement("abc3");
        v.addElement("abc4");

        //枚舉,與Iterator功能重複
        for(Enumeration<String> en=v.elements();en.hasMoreElements();){
            System.out.println("next element:"+en.nextElement());
        }

        for(Iterator<String> it=v.iterator();it.hasNext();){
            System.out.println("next:"+it.next());
        }
    }
}
package com.zj.list.demo;

import java.util.ArrayList;
import java.util.Iterator;

import com.zj.bean.Person;

public class ArrayListDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ArrayList al=new ArrayList();
        al.add(new Person("zhangsan",21));
        al.add(new Person("lisi",22));
        al.add(new Person("wangwu",23));
        al.add(new Person("zhaoliu",24));

        for(Iterator<Person> it=al.iterator();it.hasNext();){
            //直接打印it.next(),打印的是類型加哈希值。必須進行強制轉換,然後再打印
            Person p=(Person)it.next();
//          System.out.println(p.getName()+":"+p.getAge());
        }

        al.add(5);//等價於al.add(new Integer(5));當基本數據類型值賦給引用數據類型時,自動裝箱;當引用數據類型和基本數據類型運算時自動拆箱

        test2();
    }

    /**
     * 練習:去除集合中重複的元素
     */
    public static void test2() {
        ArrayList al=new ArrayList();
//      al.add("abc1");
//      al.add("abc2");
//      al.add("abc3");
//      al.add("abc4");
//      al.add("abc1");
//      al.add("abc3");
//      al.add("abc3");

        Person p=new Person("zhaoliu",27);

        al.add(new Person("zhangsan",21));
        al.add(new Person("lisi",22));
        al.add(p);
        al.add(new Person("zhaoliu",23));
        al.add(new Person("wangwu",24));
        al.add(new Person("wangwu",24));
        al.add(p);

        System.out.println(al);
        al=getSingleElement(al);
        System.out.println(al);

        System.out.println(new Person("zhaoliu",27).equals(p));
        System.out.println(al.remove(new Person("lisi",22)));//remove底層使用的也是equals()方法
        System.out.println(al);
    }

    public static ArrayList getSingleElement(ArrayList al) {
        // TODO Auto-generated method stub
        //1.定義一個臨時容器
        ArrayList temp=new ArrayList();
        //2.遍歷al集合
        for(Iterator it=al.iterator();it.hasNext();){
            Object obj=it.next();
            //3.判斷被迭代的元素是否在temp中存在
            if(!temp.contains(obj)) temp.add(obj);//contains()方法依據的是equals方法,所以重寫Person中的equals()方法即可
        }
        return temp;
    }

}
package com.zj.list.demo;

import java.util.Iterator;
import java.util.LinkedList;

public class LinkedListDemo {

    public static void main(String[] args) {
        show();
    }

    public static void show() {
        LinkedList<String> link=new LinkedList<String>();
        link.addFirst("abc1");
        link.addFirst("abc2");
        link.add("abc3");
        link.add("abc4");
        System.out.println(link);
//      System.out.println(link.getFirst());//獲取第一個但是不刪除,如果鏈表爲空,則拋出NoSuchElementException
//      System.out.println(link.removeFirst());//獲取第一個並刪除,如果鏈表爲空,則拋出NoSuchElementException
//      System.out.println(link);
//      
//      JDK1.6:
//      System.out.println(link.peekFirst());//獲取第一個但是不刪除,如果鏈表爲空則返回null
//      System.out.println(link.pollFirst());//獲取第一個並刪除,如果鏈表爲空則返回null
//      System.out.println(link);

        while(!link.isEmpty()){
            System.out.println("removeFirst:"+link.removeFirst());
        }

        for(Iterator<String> it=link.iterator();it.hasNext();){
            System.out.println(it.next());
        }

    }
}
package com.zj.bean;

public class Person implements Comparable{
    private String name;
    private int age;

    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public int hashCode() {
//      System.out.println("hashcode:"+this);
        return name.hashCode()+age*39;//乘以一個數,保證哈希值唯一,減少equals()方法調用的次數,提高效率
    }

    @Override
    public boolean equals(Object obj) {
//      System.out.println("equals:"+this);
        if(this==obj) return true;//如果是同一個對象則直接返回true,不用再比較name和age
        if(!(obj instanceof Person))//如果對象類型不相同,則拋出異常,也不用再比較
            throw new ClassCastException("類型錯誤");
        if(this.name.equals(((Person)obj).name) && this.age==((Person)obj).age) 
            return true;
        else return false;
    }

    public String toString(){
        return name+":"+age;
    }

    //Comparable接口強行對實現它的每個類的對象進行整體排序。這種排序被稱爲類的自然排序,類的 compareTo 方法被稱爲它的自然比較方法。
    @Override
    public int compareTo(Object o) {
        if(!(o instanceof Person)) 
            throw new ClassCastException("類型錯誤");
        Person p=(Person)o;
//      if(this.name.compareTo(p.name)>0)return 1;
//      else if(this.name.compareTo(p.name)==0){
//          if(this.age==p.age) return 0;
//          return (this.age>p.age)?1:-1;
//      }else return -1;

//      int temp=this.name.compareTo(p.name);
//      return temp==0?this.age-p.age:temp;

        int temp=p.name.compareTo(this.name);
        return temp==0?p.age-this.age:temp;
    }


}

五.Set接口(集合)
Set集合是一種不包含重複元素的Collection,即Set的構造函數有一個約束條件,傳入的Collection參數不能包含重複的元素。Set不保證元素的順序,即爲無序的。下面將介紹Set中的兩個主要的實現類HashSet和TreeSet。

1.HashSet
內部數據結構是哈希表,是不同步的。如何保證該集合中元素的唯一性?
通過對象的hashCode和equals方法來判斷唯一性。如果對象的hashCode值不相同,則不用判斷equals方法,直接存儲到哈希表中;如果hashCode值相同,則使用equals方法再次判斷,若爲true則視爲相同元素,否則視爲不同元素。
總結:ArrayList中的contains()方法,僅僅使用equals方法,HashSet則使用hashCode()和equals()方法。

2.TreeSet
可以對Set集合中的元素進行排序,是不同步的。如何保證集合中元素的唯一性,並保證一定的順序性?
TreeSet對元素的排序方式一:
讓元素自身具備比較功能,對象實現Comparable接口,通過對象的compareTo方法來判斷大小。返回0,則爲相同元素;若爲正數則大於;若爲負數則小於。
如果不按照對象中具備的自然順序排序,或對象中不具備自然順序,則可以使用TreeSet集合的第二種排序方式。
TreeSet對元素的排序方式二:
讓集合自身具備比較功能,定義一個類實現Comparator接口,覆蓋compare方法。將該類對象作爲參數傳遞給TreeSet集合的構造函數。

package com.zj.set.demo;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;

import com.zj.bean.Person;

public class HashSetDemo {
    public static void main(String[] args){
//      HashSet hs=new HashSet();
//      
//      hs.add("haha");//不保證有序
//      hs.add("xixi");
//      hs.add("hehe");
//      hs.add("heihei");
//      hs.add("hehe");//不允許重複,保證唯一
//      hs.add("hehe");
//      String s;
//      for(Iterator it=hs.iterator();it.hasNext();){
//          System.out.println(it.next());
//      }

        test();
        test2();
    }

    public static void test2() {
        //LinkedHashSet保證按元素插入順序進行迭代
        HashSet hs=new LinkedHashSet();

        hs.add("haha");
        hs.add("xixi");
        hs.add("hehe");
        hs.add("heihei");
        hs.add("hehe");//不允許重複,保證唯一
        hs.add("hehe");

        for(Iterator it=hs.iterator();it.hasNext();){
            System.out.println(it.next());
        }
    }

    /**
     * 往HashSet中存儲Person對象,若姓名和年齡一樣則視爲同一個人.
     * HashSet集合數據結構是哈希表,所以存儲元素的時候,使用元素的hashcode方法來確定位置;
     * 如果位置相同,再通過equals方法來確定元素是否相同。
     */
    public static void test() {
        HashSet hs=new HashSet();
        Person p=new Person("zhaoliu",27);
        //HashSet中不允許重複,判斷使用hashCode()和equals()方法
        hs.add(new Person("zhangsan",21));
        hs.add(new Person("lisi",22));
        hs.add(p);
        hs.add(new Person("zhaoliu",23));
        hs.add(new Person("wangwu",24));
        hs.add(new Person("wangwu",24));
        hs.add(p);

        for (Iterator it = hs.iterator(); it.hasNext();) {
            Person p1=(Person)it.next();
            System.out.println(p1.getName()+":"+p1.getAge());
        }
    }
} 
package com.zj.set.demo;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

import com.zj.bean.Person;

public class TreeSetDemo {
    public static void main(String[] args){
//      test1();
//      test2();
        test3();
    }

    /**
     * 使TreeSet按元素的存入順序遍歷元素,實現有序存儲
     */
    public static void test3() {
        // TODO Auto-generated method stub
        Comparator comparator=new ComparatorByLength();
        TreeSet ts=new TreeSet(comparator);

        ts.add("ab");
        ts.add("hcdfd");
        ts.add("abz");
        ts.add("zfsgfdg");
        ts.add("adf");

        for(Iterator it=ts.iterator();it.hasNext();){//TreeSet中的元素按字典序排序
            System.out.println(it.next());
        }
    }

    public static void test2() {
        Comparator comparator=new ComparatorByName();
        TreeSet ts=new TreeSet(comparator);

        ts.add(new Person("zhangsan",21));
        ts.add(new Person("lisi",24));
        ts.add(new Person("lisi",25));
        ts.add(new Person("wangwu",22));
        ts.add(new Person("zhaoliu",25));
        ts.add(new Person("zhaoai",25));
        ts.add(new Person("zhouqi",27));
        ts.add(new Person("zhaoai",25));

        //com.zj.bean.Person cannot be cast to java.lang.Comparable
        for(Iterator it=ts.iterator();it.hasNext();){//TreeSet中的元素按字典序排序
            System.out.println(it.next());
        }

    }

    public static void test1() {
        TreeSet ts=new TreeSet();
        ts.add("abc");
        ts.add("hcd");
        ts.add("abz");
        ts.add("zfs");
        ts.add("adf");

        for(Iterator it=ts.iterator();it.hasNext();){//TreeSet中的元素按字典序排序
            System.out.println(it.next());
        }   
    }
}
package com.zj.set.demo;

import java.util.Comparator;

import com.zj.bean.Person;

public class ComparatorByName implements Comparator {

    @Override
    public int compare(Object o1, Object o2) {
        // TODO Auto-generated method stub
        if(!((o1 instanceof Person)&&(o2 instanceof Person)))
            throw new ClassCastException("類型錯誤");
        Person p1=(Person)o1;
        Person p2=(Person)o2;
        int temp=p1.getAge()-p2.getAge();
        return temp==0?p1.getName().compareTo(p2.getName()):temp;
//      return 1;//使TreeSet按元素存入順序進行遍歷
//      return -1;//使TreeSet按元素存入順序逆序進行遍歷
//      return 0;//使TreeSet只能接受一個元素
    }
}

六. Map接口(映射)
映射(map)是一個存儲關鍵字和值的關聯,或者說是“關鍵字/值”對的對象,即給定一個關鍵字,可以得到它的值。關鍵字和值都是對象,關鍵字必須是唯一的,但值是可以被複制的。

1.Map中常用的方法
Map一次添加一對元素,Collection一次添加一個元素。Map也稱爲雙列集合,Collection稱爲單列集合。Map中存儲的是鍵值對,Map集合中必須保證鍵的唯一性。Map中的常用方法:
(1)添加
value put(key,value);//返回以前與key關聯的值,若沒有針對key的映射關係,則返回null
(2)刪除
void clear();//清空Map集合
value remove(key);//如果存在一個鍵的映射關係,則將其從映射中移除
(3)判斷
boolean containsKey(key);//如果此映射包含指定鍵的映射方式,則返回true
boolean containsValue(value);//如果此映射將一個或多個鍵映射到指定值,則返回true
boolean isEmpty();//如果此映射未包含鍵值映射關係,則返回true
(4)獲取
value get(key);//返回指定鍵所映射的值,若不包含該鍵的映射關係,則返回null
int size();//獲取鍵值對的個數
(5)遍歷
Set keySet();//返回此映射中所包含的鍵的Set視圖
Set entrySet();//返回此映射中包含的映射關係的Set視圖
Collection values();//返回此映射中包含的值的Collection視圖

2.Map常用的具體實現類
(1)Hashtable:內部結構是哈希表,是同步的。不允許null作爲鍵和值。
子類Properties:用來存儲鍵值對型的配置文件信息,可以和I/O技術相結合。
(2)HashMap:內部結構是哈希表,是不同步的。允許null作爲鍵和值。
(3)TreeMap:內部結構是二叉樹,是不同步的。可以對Map集合中的鍵進行排序。

package com.zj.map.demo;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class MapDemo {

    public static void main(String[] args) {
        Map<Integer,String> map=new HashMap<Integer,String>();
//      test(map);
//      test2(map);
//      test3(map);
        test4(map);
    }

    public static void test4(Map<Integer, String> map) {
        map.put(1001, "zhaoliu");
        map.put(1002, "wangwu");
        map.put(1003, "lisi");
        map.put(1004, "zhangsan");
        map.put(1005, "lisi");

        Collection<String> values=map.values();//values方法返回此映射中包含的值的Collection視圖,Collection允許重複元素
        for(Iterator<String> it=values.iterator();it.hasNext();){
            System.out.println(it.next());
        }
    }

    public static void test3(Map<Integer, String> map) {
        // TODO Auto-generated method stub
        map.put(1001, "zhaoliu");
        map.put(1002, "wangwu");
        map.put(1003, "lisi");
        map.put(1004, "zhangsan");

        //取出map中的所有元素。
        //方式二:
        //原理:先通過entrySet方法獲取映射中包含的映射關係所組成的set集合,再通過set的迭代器獲取到每一個映射關係
        Set<Map.Entry<Integer, String>> entrySet=map.entrySet();//獲取映射中包含的映射關係的set集合
        for(Iterator<Map.Entry<Integer, String>> it=entrySet.iterator();it.hasNext();){
            Map.Entry<Integer, String> entry=(Map.Entry<Integer, String>)it.next();
            //通過Map.Entry對象的getKey和getValue方法來獲得鍵和值
            System.out.println(entry.getKey()+":"+entry.getValue());
            //System.out.println(entry.toString());
        }
    }

    public static void test2(Map<Integer, String> map) {
        map.put(1001, "zhaoliu");
        map.put(1002, "wangwu");
        map.put(1003, "lisi");
        map.put(1004, "zhangsan");

        //取出map中的所有元素。
        //方式一:
        //原理:先通過keySet方法獲取map中所有的鍵所在的set集合,再通過set的迭代器獲取到每一個鍵,對每一個鍵獲取其對應的值即可
        Set<Integer> keySet=map.keySet();//獲取映射中所有鍵值組成的set集合
        for(Iterator it=keySet.iterator();it.hasNext();){
            Integer key=(Integer)it.next();
            System.out.println(key+":"+map.get(key));
        }
        System.out.println(map);
    }

    public static void test(Map<Integer,String> map){//學號和姓名

        //1.添加元素
        System.out.println(map.put(1001, "zhangsan"));
        map.put(1003, "zhaoliu");
        System.out.println(map.put(1002, "lisi"));
        System.out.println(map.put(1002, "wangwu"));//存相同鍵,值會覆蓋
        map.put(1004, "zhouqi");

        System.out.println(map);
        //2.刪除
        map.remove(1002);
        System.out.println(map);

        //3.判斷
        System.out.println(map.containsKey(1003));

        //4.獲取
        System.out.println(map.get(1004));  
    }
}
package com.zj.map.demo;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import com.zj.bean.Student;

public class HashMapDemo {

    public static void main(String[] args) {
        test();
    }

    /**
     * 將學生對象和學生的歸屬地通過鍵與值存儲到map集合中
     */
    public static void test() {
        HashMap<Student,String> hm=new HashMap<Student,String>();
        hm.put(new Student("zhangsan",24), "北京");
        hm.put(new Student("lisi",22), "上海");
        hm.put(new Student("wangwu",23), "杭州");
        hm.put(new Student("zhaoliu",26), "蘇州");
        hm.put(new Student("wangwu",23), "杭州");

        Set<Student> keySet=hm.keySet();
        for(Iterator<Student> it=keySet.iterator();it.hasNext();){
            Student key=it.next();
            System.out.println(key.getName()+":"+key.getAge()+"--"+hm.get(key));
        }
    }
}
package com.zj.map.demo;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import com.zj.bean.Student;
import com.zj.set.demo.ComparatorByName;

public class TreeMapDemo {

    public static void main(String[] args) {
        test();
    }

    /**
     * 將學生對象和學生的歸屬地通過鍵與值存儲到map集合中
     */
    public static void test() {
        TreeMap<Student,String> tm=new TreeMap<Student,String>(new ComparatorByName());
        tm.put(new Student("zhangsan",24), "北京");
        tm.put(new Student("lisi",22), "上海");
        tm.put(new Student("wangwu",23), "杭州");
        tm.put(new Student("zhaoliu",26), "蘇州");
        tm.put(new Student("wangwu",23), "杭州");

//      Set<Student> keySet=tm.keySet();
//      for(Iterator<Student> it=keySet.iterator();it.hasNext();){
//          Student key=it.next();
//          System.out.println(key.getName()+":"+key.getAge()+"--"+tm.get(key));
//      }

        Set<Map.Entry<Student,String>> entrySet=tm.entrySet();
        for(Iterator<Map.Entry<Student,String>> it=entrySet.iterator();it.hasNext();){
            Map.Entry<Student,String> entry=it.next();
            System.out.println(entry.getKey().getName()+"::"+entry.getKey().getAge()+"---"+entry.getValue());
        }
    }

}
package com.zj.bean;

public class Student extends Person {

    public Student(String name, int age) {
        super(name, age);
    }
}

七. Utilities(靜態工具類)

1. Collections
Collections工具類代碼演示:

package com.zj.collections.demo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.zj.set.demo.ComparatorByLength;

public class CollectionsDemo {

    public static void main(String[] args) {
        /*
         * Collections:是集合框架的工具類,裏面的方法都是靜態的
         */

//      test1();
        test2();
        test3();
    }

    public static void test3() {
        List<String> list=new ArrayList<String>();
        List synList=Collections.synchronizedList(list);//返回指定列表支持的同步列表
    }

    public static void test2() {
        List<String> list=new ArrayList<String>();

        list.add("adsdf");
        list.add("df");
        list.add("hgadsdf");
        list.add("ad");
        list.add("ggfhadsdf");
        list.add("zxc");

        System.out.println(list);

        Collections.sort(list);
        System.out.println(list);

//      Collections.reverse(list);//反轉指定列表中元素的順序
//      System.out.println(list);

//      Comparator comp=Collections.reverseOrder();// 返回一個比較器,它強行逆轉實現了 Comparable 接口的對象 collection 的自然順序。
//      Collections.sort(list, comp);
//      System.out.println(list);

        Comparator comp2=Collections.reverseOrder(new ComparatorByLength()); 
        Collections.sort(list, comp2);
        System.out.println(list);
    }

    public static void test1() {
        List<String> list=new ArrayList<String>();

        list.add("adsdf");
        list.add("df");
        list.add("hgadsdf");
        list.add("ad");
        list.add("ggfhadsdf");
        list.add("zxc");

        System.out.println(list);

        String max=Collections.max(list);//獲取最大的
        System.out.println("max="+max);

        String maxLen=Collections.max(list, new ComparatorByLength());//獲取最長的
        System.out.println("maxLen="+maxLen);

        Collections.sort(list);//對list集合進行自然順序的排序
        System.out.println(list);

//      mySort(list);
//      System.out.println(list);//使用自己定義的mySort(List)方法進行排序

        int index=Collections.binarySearch(list,"zxc");
        System.out.println("index="+index);

//      Collections.sort(list, new ComparatorByLength());//根據指定比較器產生的順序對指定列表進行排序
//      System.out.println(list);

        mySort(list, new ComparatorByLength());//使用自己定義的mySort(List,Comparator)方法,根據指定的比較器進行排序
        System.out.println(list);
    }

    public static <T extends Comparable <? super T>>void mySort(List<T> list){
        for(int i=0;i<list.size();i++){
            for(int j=i+1;j<list.size();j++){
                if(list.get(i).compareTo(list.get(j))>0){
//                  T temp=list.get(i);
//                  list.set(i, list.get(j));
//                  list.set(j, temp);
                    Collections.swap(list, i, j);
                }   
            }
        }   
    }   

    public static <T extends Comparable <? super T>>void mySort(List<T> list,Comparator<? super T> c){
        for(int i=0;i<list.size();i++){
            for(int j=i+1;j<list.size();j++){
                if(c.compare(list.get(i), list.get(j))>0){
//                  T temp=list.get(i);
//                  list.set(i, list.get(j));
//                  list.set(j, temp);
                    Collections.swap(list, i, j);
                }   
            }
        }   
    }   
}

2. Arrays
Arrays工具類代碼演示:

package com.zj.arrays.demo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArraysDemo {
    public static void main(String[] args) {
        /*
         * Arrays:集合框架工具類,裏面的方法都是靜態的
         */
//      int[] arr={1,3,5,2,7,8,9,0};
//      System.out.println(myToString(arr));
//      
//      System.out.println(Arrays.toString(arr));

//      test1();
        test2();
    }
    /**
     * 重點:Collection接口中的toArray方法,將集合轉成數組
     * 好處:集合轉成數組,可以對集合中元素的操作方法進行限定,不允許執行增刪操作
     */
    public static void test2() {
        // TODO Auto-generated method stub
        List<String> list =new ArrayList<String>();
        list.add("fsdf");
        list.add("hgfhd");
        list.add("asd");

        //注意:toArray方法需要傳入一個指定類型、指定長度的數組。
        //     如果長度小於集合的size,那麼該方法會創建一個和集合相同size的數組;
        //     如果長度大於集合的size,那麼該方法會就會使用指定的數組存儲集合中的元素,其他位置默認爲null;
        //     所以建議,最後長度指定爲集合的size
        String[] arr=list.toArray(new String[list.size()]);
        System.out.println(Arrays.toString(arr));

    }

    /**
     * 重點:List asList(arr),將數組轉成集合
     * 好處:Arrays.asList通過可以使用集合的方法操作數組中的元素,與Collection.toArray一起充當數組與集合之間的橋樑
     * 注意:數組的長度是固定的,所以對於集合的增刪方法是不可以使用的,否則會發生java.lang.UnsupportedOperationException
     */
    public static void test1() {
        String[] arr1={"ads","afdfdsf","nkk","fdjk"};
        List list1=Arrays.asList(arr1);

        System.out.println(list1.contains("nkk"));

//      list.add("aaa");// 發生java.lang.UnsupportedOperationException,不支持的操作異常,不支持增刪操作
        System.out.println(list1);

        //注意:如果數組中的元素是對象,那麼轉成集合時,直接將數組中的元素作爲集合中的元素進行集合存儲
        //       如果數組中的元素是基本數據類型數值,那麼會將該數組作爲集合中的元素進行存儲,因爲集合只能存儲對象,不能存儲基本數據類型
        int[] arr2={2,4,6,7,1};
        List<int[]> list2=Arrays.asList(arr2);
        System.out.println(list2);//list2中只有1個int[]數組對象

        Integer[] arr3={2,4,6,7,1};
        List<Integer> list3=Arrays.asList(arr3);
        System.out.println(list3);//list3中有5個Integer對象
    }

    //源碼:toString的經典實現
    public static String myToString(int[] a) {
        if (a == null)
            return "null";
        int iMax = a.length - 1;
        if (iMax == -1)
            return "[]";

        StringBuilder b = new StringBuilder();
        b.append('[');
        for (int i = 0; ; i++) {//中間省略了條件判斷,提高了效率(這種代碼寫法值得借鑑)
            b.append(a[i]);
            if (i == iMax) return b.append(']').toString();
            b.append(", ");
        }
        /*for (int i = 0; i<= iMax ; i++) {//中間判斷,下面也要判斷,效率低
            b.append(a[i]);
            if (i == iMax) b.append("]");
            else b.append(", ");
        }
        return b.toString();*/    
    }
}
發佈了40 篇原創文章 · 獲贊 7 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章