黑馬程序員——Java基礎知識——集合框架、集合工具類、Arrays

------Java培訓、Android培訓、iOS培訓、.Net培訓、期待與您交流! 

一、集合概述

        集合框架圖:

          

  這就是Java中集合框架的體系,在以後的使用中參考頂層接口,創建底層對象。

  一、爲什麼出現集合類?

           面嚮對象語言對事物的體現都是以對象的形式,爲了方便對多個對象的操作,就對對象進行存儲,集合就是存儲對象最常用的一種方式。

 二、數組和集合類同是容器,有何不同?

          數組雖然也可以存儲對象,但長度是固定的;集合長度是可變的。數組中可以存儲基本數據類型,集合只能存儲對象。 

 三、爲什麼有這麼多集合?集合的特點又是什麼?

          集合就是一個容器,存儲的是對象的引用(地址),因爲每一個容器對數據的存儲方式都有所不同,這個存儲方式稱爲:數據結構。集合只用於存儲對象,集合的長度是可變的,可以存儲不同類型的對象。          

 

二、Collection

       Collection是集合框架中的常用接口。我們經常使用的是它的兩個子接口(ListSet)的子類。

            Collection

                     |----List:元素是有序的,元素可以重複。因爲該集合體繫有索引。

                     |-----Set:元素是無序的,元素不可以重複。

       Collection共性方法:

                     1.添加

                          boolean  add(Object obj)  傳入的參數類型是Object類型,以便接收任意類型對象。       

                     2.刪除 

                      boolean remove(Object obj) 

                         boolean removeAll(另一集合)   只保留另一集合中沒有的元素。

                      void   clear()  清空集合

                      3.判斷

                         contains(Object obj);//判斷集合中是否存在指定元素

                         isEmpty();//判斷集合是否爲空

                      4、獲取集合的長度

                         int   size();

                      5、取交集

                         boolean   retainAll(另一集合)//調用者只保留和被調用者中相同的元素,被調用的集合不變,若無交集,調用者變成空。

       下面用代碼進行演示:

       //創建集合
	   Collection coll=new ArrayList();
	   //添加元素
	   coll.add("java01");
	   coll.add("java02");
	   coll.add("java03");
	   //獲取集合的長度
	   coll.size();
	   //刪除元素
	   coll.remove("java02");
	   //判斷元素是否存在於集合中
	   boolean b= coll.contains("java03");
	   //清空集合
	   coll.clear();
 迭代:

          迭代是取出集合中元素的一種方式。對於集合的元素取出這個動作:不足以用一個函數來描述,需要用多個功能來體現,所以就將取出這個動作封裝成一個對象來描述。就把取出方式定義在集合的內部,這樣取出方式就可以直接訪問集合內部的元素,那麼取出方式就被定義成了內部類。每一個容器的數據結構不同,所以取出的動作細節也不同,但是都有共性內容:判斷和取出。那麼就將共性抽取。抽取出來的規則就是Iterator(迭代器),通過一個對外提供的方法:iterator(),來獲取集合中的迭代器。Collection的子類集合對象中都有迭代器。

          下面通過一段代碼,介紹迭代器的獲取和具體方法的使用。如下:

       //創建集合
	   Collection coll=new ArrayList();
	   //添加元素
	   coll.add("java01");
	   coll.add("java02");
	   coll.add("java03");
	   coll.add("java03");
	   //通過iterator方法,獲取迭代器
	   Iterator it=coll.iterator();
	   //hasNext()方法 :判斷是否還有下一個元素,有則返回true。
	   while(it.hasNext()){
		    //next()方法:取出下一個元素
		   String s=(String)it.next();
		   System.out.println(s);
		   if("java01".equals(s))
	            //迭代器中在迭代過程中可以通過remove方法移除指定元素
		     it.remove();
         }
	   //在迭代循環過程中,next調用一次,就用hasNext()判斷一次。
	   	   
          迭代器在Collection接口中是通用的,它替代了Vector類中的Enumeration(枚舉)。迭代器的next方法是自動向下取出元素,要避免出現NoSuchElementException。迭代器中的next方法返回值類型是Object,要記得類型轉換。

三、List

        List:元素是有序的,元素可以重複。因爲該集合體繫有索引。

              |--ArrayList:底層的數據結構使用的是數組結構。特點:查詢速度很快。但是增刪稍慢。線程不同步。

              |--LinkedList:底層使用的是鏈表數據結構。特點:增刪速度很快,查詢稍慢。

              |--Vector:底層是數組數據結構。線程同步。被ArrayList替代了。


        List的特有方法:List的方法都是可以操作腳標的方法。例如:

        1、增加

        void  add(index,element);//指定位置添加元素

        boolean  addAll(index,Collection);//在指定位置增加給定集合中的所有元素,若省略位置參數,則在當前集合的後面依次添加元素

       2、刪除

         remove(index);//刪除指定位置的元素,返回被刪除的元素

       3、修改

        set(index,element);//修改指定位置的元素。返回被修改的元素

       4、獲取

        get(index);//通過腳標獲取元素

        subList(from,to);//獲取部分對象元素

        5、其他

        listIterator();//List特有的迭代器

        indexOf(obj);//獲取元素第一次出現的位置,如果沒有則返回-1

    List集合判斷元素是否相同,移除等操作,依據的是元素的equals方法。

     ListIterator:

            ListIterator是List集合特有的迭代器,是Iterator的子接口。在迭代時,ListIterator除了可以對元素進行判斷、取出、刪除外,還具備添加元素,修改元素的功能。通過List集合的listIterator方法獲取。下面一段代碼對其進行演示:

            List list=new ArrayList();
	   //添加元素
	   list.add("java01");
	   list.add("java02");
	   list.add("java03");
	   list.add("java03");
	   //通過listIterator方法,獲取迭代器
	   ListIterator it=list.listIterator();
	   while(it.hasNext()){
		   String s=(String)it.next();
		   System.out.println(s);
		   if("java01".equals(s))
			//迭代器中在迭代過程中修改指定元素
		        it.set("haha");
		       //添加元素,
		       it.add("no");
	   }   
         LinkedList:底層是鏈表結構。特有方法如下:

         1.增加:addFirst();addLast();
         2.獲取:getFirst();getLast();
                        獲取元素,但不刪除元素。如果集合中沒有元素,會出現NoSuchElementException
         3.刪除:removeFirst();removeLast();
                        獲取元素,但是元素被刪除。如果集合中沒有元素,會出現NoSuchElementException
        JDK1.6出現了替代方法:

         1.增加:offerFirst();offerLast();
         2.獲取:peekFirst();peekLast();

                        獲取元素,但不刪除元素。如果集合中沒有元素,會返回null。
         3.刪除:pollFirst();pollLast();
                        獲取元素,但是元素被刪除。如果集合中沒有元素,會返回null。

         下面是利用LinkedList的一段程序,如下:

/**
需求:使用LinkedList模擬一個隊列數據結構。
隊列:先進先出 First in First out  FIFO 如同一個水管。
*/
class DuiLie
{
	//定義一個LinkedList引用,成員方法可以使用其方法
        private LinkedList link;
        DuiLie()
	{
		link = new LinkedList();
	}
	//定義添加方法
	public void myAdd(Object obj)
	{
		link.addFirst(obj);
	}
	//定義獲取方法
        public Object myGet()
	{
		return link.removeLast();
	}
	//判斷是否爲空
        public boolean isNull()
	{
		return link.isEmpty();
	}

}

class  LinkedListTest
{
	public static void main(String[] args) 
	{
		//建立隊列對象
                DuiLie dl = new DuiLie();
		//添加元素
                dl.myAdd("java01");
		dl.myAdd("java02");
		dl.myAdd("java03");
		dl.myAdd("java04");
                //取出元素
                 while(!dl.isNull())
                   System.out.println(dl.myGet());
	}
}


四、Set

        Set:元素是無序的(存入和取出的順序不一定一致),元素不可以重複

            |——HashSet:底層結構是哈希表,線程不同步,保證元素唯一性的原理:判斷元素的hashCode值是否相同,如果相同,還會繼續判斷元素的equals方法,返回值是否爲true。

           |——TreeSet: 底層是二叉樹結構,可以對Set集合中的元素進行排序,默認按照字母的自然順序,保證元素唯一性的一句:compareTo方法,返回值是否爲0。

        Set集合的操作方法和Collection是一致的。

         1.HashSet:

              線程不安全,存取速度塊。可以通過元素的兩個方法hashCode和equals來保證元素的唯一性。如果hashCode值相同,才判斷equals方法的返回值是否爲true;如果hashCode不同,不調用equals方法。HashSet中判斷元素是否存在,以及刪除等操作,依據的都是元素的hashCode和equals方法下面通過一段代碼,對HashSet的使用進行學習。如下:

/**
需求:往hashSet集合中存入自定義對象
      姓名和年齡相同爲同一個人,重複元素。
*/
class HashSetDemo 
{
	public static void main(String[] args) 
	{
		//建立HashSet集合
                HashSet hs = new HashSet();
                //添加元素
		hs.add(new Student("小明",11));
		hs.add(new Student("大明",12));
		hs.add(new Student("阿亮",13));
		hs.add(new Student("小明",12));
		hs.add(new Student("老羅",14));	
		//對元素進行迭代 
		Iterator it = hs.iterator();
                while(it.hasNext())
		{
			Student s= (Student)it.next();
			System.out.println(s.getName()+"::"+s.getAge());
		}
	}
}
//定義學生類
class Student
{       
        //定義學生的姓名和年齡屬性
	private String name;
	private int age;
	Student(String name,int age)
	{
		this.name = name;
		this.age = age;
	}
	//複寫hashCode方法,自定義對象的hashCode算法
	public int hashCode()
	{
		return name.hashCode()+age*37;
	}
        //複寫equals方法。
	public boolean equals(Object obj)
	{
            //判斷傳入對象是否是本類型
	    if(!(obj instanceof Student))
		  return false;
            //向下轉換 
            Student s = (Student)obj;
	    //姓名和年齡都相同時,返回true,爲相同的對象。
            return this.name.equals(p.name) && this.age == p.age;
	}

	public String getName()
	{
		return name;
	}
	public int getAge()
	{
		return age;
	}
}

     2.TreeSet

          可以對Set集合中的元素進行排序。

        特點:

          1.底層的數據結構是二叉樹結構。

          2.可讀Set集合中的元素進行排序,是因爲TreeSet類實現了Comparable接口,該接口強制對增加到集合的對象進行了比較,需要複寫comparrTo方法,才能讓對象滿足需求(如:比較人的年齡大小)繼續排序,加入集合。Java中的很多類都具備比較性其實就是實現了Comparable。當排序時的主要條件相同時,會按次要條件排序。

          3.保證數據的唯一性的一句:通過compareTo方法的返回值,返回值爲正整數、負整數和0,爲0時元素爲相同對象不存入集合。

     TreeSet有兩種對添加元素進行比較的方法:自然排序和比較器排序。

         (1)自然排序:讓元素自身具備比較性,元素需要實現Comparable接口,覆蓋compareTo方法,這種放稱爲元素的自然排序,或者加默認排序。下面通過代碼進行演示:

/**
需求:往TreeSet集合中存入自定對象
      姓名和年齡相同爲同一個人,重複元素。
      並按年齡的大小排序。
      年齡相同 ,按姓名首字母的自然順序排序。
*/
class TreeSetDemo
{
	public static void main(String[] args) 
	{
		 //建立TreeSet集合
                TreeSet ts = new TreeSet();
                //添加元素
		ts.add(new Student("小明",11));
		ts.add(new Student("大明",12));
		ts.add(new Student("阿亮",13));
		ts.add(new Student("小明",12));
		ts.add(new Student("老羅",14));	
		//對元素進行迭代 
		Iterator it = ts.iterator();
                while(it.hasNext())
		{
			Student s= (Student)it.next();
			System.out.println(s.getName()+"::"+s.getAge());
		}
	}
}
//定義學生類,實現Comparable接口
class Student implements Comparable
{       
        //定義學生的姓名和年齡屬性
	private String name;
	private int age;
	Student(String name,int age)
	{
		this.name = name;
		this.age = age;
	}
	//複寫compareTo方法,按年齡大小進行比較,年齡相同,比較姓名
        public int compareTo(Object obj)
        {   if(!(obj instanceof Student))
        	      throw new ClassCastException("該對象不是學生類型");
            Student s=(Student)obj;
        	if(this.age==s.age)
                    return this.name.compareTo(s.name);
             return this.age-s.age;
        }

	public String getName()
	{
		return name;
	}
	public int getAge()
	{
		return age;
	}
}
   使用這種方法對元素進行排序,要求元素自身必須具備比較性。  

   (2)比較器:當元素自身不具備比較性時,或者具備的比較性不是所需要的,這時就讓集合自身具備比較性。當集合初始化時,就有了比較方式。定義一個比較器,將比較器對象作爲參數傳給TreeSet集合的構造函數。

     比較器構造方式:定義一個類,實現Comparator接口,需要覆蓋compare方法。注意當兩種排序方式都存在時,以比較器爲主。如下面的程序:

/**
需求:往TreeSet集合中存入自定對象
      姓名和年齡相同爲同一個人,重複元素。
      以姓名的長短排序,姓名的長度相同時,以年齡大小排序
     使用比較器。
*/
class ReflectTest1
{
	public static void main(String[] args) 
	{
		//建立TreeSet集合,傳入比較器對象
        TreeSet ts = new TreeSet(new MyComparator());
        //添加元素
		ts.add(new Student("小明",11));
		ts.add(new Student("王大明",12));
		ts.add(new Student("李阿亮",13));
		ts.add(new Student("歐陽小明",12));
		ts.add(new Student("老羅",14));	
		//對元素進行迭代 
		Iterator it = ts.iterator();
                while(it.hasNext())
		{
			Student s= (Student)it.next();
			System.out.println(s.getName()+"::"+s.getAge());
		}
	}
}
//定義一個比較器,實現Comparator接口
class MyComparator implements Comparator
{
	//複寫compare方法,定義以姓名長短的比較方法。長短相同時比較年齡大小
	public int compare(Object o1,Object o2)
	{
		if(!(o1 instanceof Student )&&!(o2 instanceof Student))
			throw new ClassCastException("對象不是學生類型");
		Student s1=(Student)o1;
		Student s2=(Student)o2;
		int num=0;
		if((num=s1.getName().length()-s2.getName().length())==0)
			return s1.getAge()-s2.getAge();
		return  num;
	}
}
//定義學生類
class Student implements Comparable
{       
        //定義學生的姓名和年齡屬性
	private String name;
	private int age;
	Student(String name,int age)
	{
		this.name = name;
		this.age = age;
	}
	//複寫compareTo方法,按年齡大小進行比較 
        public int compareTo(Object obj)
        {   if(!(obj instanceof Student))
        	      throw new ClassCastException("該對象不是學生類型");
            Student s=(Student)obj;
        	if(this.age==s.age)
                    return this.name.compareTo(s.name);
             return this.age-s.age;
        }

	public String getName()
	{
		return name;
	}
	public int getAge()
	{
		return age;
	}
}

五、Map

        Map<k、v>集合是一個接口,和List集合以及Set集合不同的是,它是雙列集合,並且可以給對象加上名字,即鍵(Key).該集合存儲鍵值對,一對一往裏存。存入元素時要保證鍵的唯一性。

        Map
           |-----HashTable :底層是哈希表結構,不可以存入null鍵,null值,線程同步,JDK1.0出現,效率低。

           |-----HashMap :  底層是哈希表結構,可以存入null鍵,null值,線程不同步,JDK1.2出現。效率高。

           |-----TreeMap:    底層是二叉樹結構。線程不同步,可以用於給Map集合中的鍵排序。 

           Map和Set很像,其實Set底層就是使用了Map集合。

         Map的常用方法:

             1.添加

                   V     put(K key,V value);添加元素,如果添加元素時,出現相同的鍵,後添加的值會覆蓋原有鍵對應的值,並返回被覆蓋的值。

                  void   putAll(Map<? extends  K,? extends V> m);添加一個集合。

             2.刪除

                  V  remove(Object key)刪除指定映射關係,返回被刪除的映射關係中的值。  

                  void  clear() 清空集合

           3.判斷

                containsKey(Object key) 判斷是否含有指定鍵

                containsValue(Object Value) 判斷是否含有指定值

                isEmpty() 集合是否爲空

          4.獲取

                 V  get(Object key)  獲取指定鍵對應的值,HashMap集合中可以通過get()方法的返回值判斷一個鍵是否存在。返回null不                                                存在

                     size()  獲取集合的長度

                     values();返回集合中的所有值。

            下面通過代碼對Map中的方法進行演示,如下:

        Map<String,String> map = new HashMap<String,String>();
        //添加元素,如果添加時,出現相同的鍵。那麼後添加的值會覆蓋原有鍵對應值。
        map.put("01","張三");
        map.put("01","李四");
	map.put("02","王五");
	map.put("03","陳六");
        //刪除鍵值對
        map.remove("01");
        //獲取指定鍵的對應值   
	map.get("02");
        //獲取集合的長度
	map.size();
	//獲取map集合中所有的值。
	Collection<String> coll = map.values();


    Map集合取出元素:

        將Map集合轉換成Set集合,再通過迭代器取出。具體方法有以下兩種:

    1.Set<k> keySet():將Map中的所有的鍵存到Set集合中,因爲Set具備迭代器。所以通過迭代方式取出所有的鍵,再通過get方法獲取每個鍵對應的值。

     2.Set<Map.Entry<K、V>> entry():將Map集合中的映射關係存放到Set集合中,而這個關係的數據類型是:Map.Entry。Entry是一個接口,它是Map接口中的一個內部接口,可以通過它具有的getKey()和getValue()方法獲得對應的鍵和值。

      這裏還要對Map.Entry做一個介紹:Map.Entry之所以定義在內部,是因爲Map集合中存在的是映射關係的兩個數據,是先有Map集合,纔可以有映射關係的存在,而且此類關係是集合的內部事務,這個映射關係可以直接訪問Map集合中的成員,所以定義在集合內部。

      下面通過一段程序,分別表示Map取出元素的兩種方式:

<pre name="code" class="java">                //創建Map集合,這裏用到了泛型。
		Map<String,String> map = new HashMap<String,String>();
                //添加元素,如果添加時,出現相同的鍵。那麼後添加的值會覆蓋原有鍵對應值。
		map.put("01","張三");
		map.put("01","李四");
		map.put("02","王五");
		map.put("03","陳六");
       
		//第一種:將Map中所有的鍵存到Set集合中
		Set<String> keyset=map.keySet();
		//對set集合進行迭代
		Iterator<String> it=keyset.iterator();
		while(it.hasNext()){
			//獲取鍵
			String key=it.next();
			//通過map的get方法,獲取對應值
			String value=map.get(key);
		    System.out.println(key+"..."+value);
		}
		
		//第二種:將Map中的所有映射關係存放到Set中
		Set<Map.Entry<String, String>> entryset=map.entrySet();
		Iterator<Map.Entry<String, String>> it1=entryset.iterator();
		while(it1.hasNext()){
			Map.Entry<String, String> me=it1.next();
			//通過Map.Entry的方法,獲取鍵和對應的值
			String key=me.getKey();
			String value=me.getValue();
			System.out.println(key+"..."+value);	
		}

	}



下面是一段Map集合使用的練習,當要存儲的數據之間存在映射關係時,就會用到map集合,如下:

/**
每一個學生都有對應的歸屬地。
學生Student,地址String。
學生屬性:姓名,年齡。
注意:姓名和年齡相同的視爲同一個學生。
保證學生的唯一性。
*/

//定義學生類,具備比較性
class Student implements Comparable<Student>
{
	private String name;
	private int age;
	Student(String name,int age)
	{
		this.name = name;
		this.age = age;
	}
	//複寫compareTo方法,以年齡大小爲比較的主要條件
	public int compareTo(Student s)
	{
		int num = this.age-s.age;
		if(num==0)
			return this.name.compareTo(s.name);
		return num;
	}
        //複寫hashCode方法
	public int hashCode()
	{
		return name.hashCode()+age*34;
	}
	public boolean equals(Object obj)
	{
		if(!(obj instanceof Student))
			throw new ClassCastException("類型不匹配");

		Student s = (Student)obj;

		return this.name.equals(s.name) && this.age==s.age;
		

	}
	public String getName()
	{
		return name;
	}
	public int getAge()
	{
		return age;
	}
	public String toString()
	{
		return name+":"+age;
	}
}
class  MapTest
{
	public static void main(String[] args) 
	{
		HashMap<Student,String> hm = new HashMap<Student,String>();
                //添加元素
		hm.put(new Student("lisi1",21),"beijing");
		hm.put(new Student("lisi1",21),"tianjin");
		hm.put(new Student("lisi2",22),"shanghai");
		hm.put(new Student("lisi3",23),"nanjing");
		hm.put(new Student("lisi4",24),"wuhan");

		//第一種取出方式 keySet

		Set<Student> keySet = hm.keySet();

		Iterator<Student> it = keySet.iterator();

		while(it.hasNext())
		{
			Student stu = it.next();
			String addr = hm.get(stu);
			System.out.println(stu+".."+addr);
		}


		//第二種取出方式 entrySet
		Set<Map.Entry<Student,String>> entrySet = hm.entrySet();

		Iterator<Map.Entry<Student,String>> iter = entrySet.iterator();
		
		while(iter.hasNext())
		{
			Map.Entry<Student,String> me = iter.next();
			Student stu = me.getKey();
			String addr = me.getValue();
			System.out.println(stu+"........."+addr);
		}
	}
}
   在操作,有時數據是一對多的映射,這時就需要在Map集合中嵌套一個集合。如下面的程序:

/**
一個學校中每個教室名對應一個教室,而在每一個教室中每一個學號對應一個學生名,如:
"yureban" "01" "zhangsan";
"yureban" "02" "lisi";
"jiuyeban" "01" "wangwu";
"jiuyeban" "02" "zhaoliu";
*/
class  ReflectTest1  
{  
    public static void main(String[] args)   
    {  
        //創建預熱班集合 
        HashMap<String,String> yureban=new HashMap<String,String>();  
        //創建就業班集合  
        HashMap<String,String> jiuyeban=new HashMap<String,String>();  
        //學校集合  
       HashMap<String,HashMap<String,String>> czbk=new HashMap<String,HashMap<String,String>>();  
          
        //存入教室名和對應的教室。
        czbk.put("yureban",yureban);  
        czbk.put("jiuyueban",jiuyeban);  
          
        //預熱班級中存入學號和對應的學生名。 
        yureban.put("01","zhangsan");  
        yureban.put("02","lisi");  
          
        //預熱班級中存入學號和對應的學生名。 
        jiuyeban.put("01","wangwu");  
        jiuyeban.put("02","zhouqi");  
         //獲取每個學生信息
        for (Iterator<String> it=czbk.keySet().iterator();it.hasNext();)
        {   //教室名稱
            String roomName= it.next();
            System.out.println(roomName+":");  
            //獲取到每個教室
            HashMap<String,String> stu=czbk.get(roomName);  
             //獲取每個教室中的學生信息
            for (Iterator<String> it1=stu.keySet().iterator();it1.hasNext();)  
            {   //學號、姓名
                String id=it1.next();  
                String name=stu.get(id);
                System.out.println(id+"..."+name);  
            }  
        }  
    }  
      
}


六、集合工具類

       Collections是集合框架的一個工具類,它裏面的方法都是靜態的,不需要創建對象,並沒封裝特有數據。在Collections中大部分方法是用來對List集合進行操作的,如比較、二分查找、隨機排序等。

         常見操作:

         1、排序

               sort(List<T>list)按自然順序排序

               sort(List<T>list,Comparator<? super T> c) 根據比較器排序

         2.查找

              T  max(Collection<? extends T> coll) 根據集合的自然順序,獲取最大值

              T  max(Collection<? extends T> coll,Comparator<? super T>c) 根據比較器,獲取最大值

              int   binarySearch(List<? extends Comparable<? super T> c>list,T key) 二分法查找

        3.替換

              void  fill(List<? super T>list, T obj) 集合中的元素全部替換成指定指定元素

              boolean  replaceAll(List<T>list,T oldVal,T newVal) 替換指定元素

               void swap(List list,int i,int j)位置置換

               void   shuffle(List<T>list)隨機置換

          4、反轉

               void reverse(List<?>list)

                      reverseOrder() 強行逆轉Comparable接口

                      reverseOrder(Comparator<T>comp)強行逆轉一個比較器,返回一個比較器。

          5.同步

             LIST<T>   synchronizedList(List<T> list) 返回支持的同步List集合。

             Map<K、V> synchronizedMap(Map<K、V>m) 返回支持的同步map集合。

 下面通過代碼,看一下Collections的使用,如下:

       List<String> list=new ArrayList<String>();
       list.add("abc");
       list.add("abd");
       list.add("cbd");
       list.add("a");
       //給集合中的元素排序
       Collections.sort(list);
       //取最大值
       String s=Collections.max(list);
       //替換指定元素
       Collections.replaceAll(list, "abc", "ff");
       //全部替換
       Collections.fill(list,"kkk");
       //反轉
       Collections.reverse(list); 
  Collections和Collection的區別:

          Collection是集合框架的一個頂層接口,裏面定義了單列集合的共性方法,常用的子接口是List和Set;Collections是集合框架中的一個工具類,該類中的方法都是靜態的,提供的方法可以對List集合進行排序、二分查找等方法。集合通常都是線程不安全的,因爲要提高效率,如果多線程操作這些集合時,可以通過Collections的同步方法,將不安全的集合變成安全的。


七、Arrays

       Arrays是用於操作數組的工具類,方法都是靜態的,不需要創建對象。
       常見方法:

         1.List<T>   asList(T....a) 將數組變爲集合

            把數組變成集合後,可以使用集合的方法操作數組中的元素。但要注意:.轉變後,不可以使用集合的增刪方法,因爲數組的長度是固定的,如果進行增刪操作,則產生UnsupportedOperationException異常。數組中的元素如果都是對象,則這些元素轉變後直接變成數組中的元素;如果數組中的元素都是基本數據類型,則將數組變爲集合中的一個元素存在。

        2.binarySearch、fill、sort等

            特點:可對數組進行對應操作,可以接收boolean型之外的基本數據類型及有序的應用類型數組的參數,且還可以對指定的元素的範圍,並對指定的範圍進行操作。如:sort(T[ ] a,int fromIndex,int toIndex);

       3.toString(T[]t )可以將各種類型的數組轉換爲字符串。

        如下:

       String[]str={"dbc","adef","bgh"};
        //對數組進行排序
        Arrays.sort(str);
        //查找數值,若不存在,返回-1
       int a= Arrays.binarySearch(str, "abc");
       System.out.println(a); 
       //將數組變爲字符串
        System.out.println(Arrays.toString(str));
       //將數組變爲集合。
       List list= Arrays.asList(str);
       System.out.println(list.get(1));

       注意:數組可以變成集合,集合也可以變成數組,通過Collections接口中的toArray方法。格式:<T>T[] toArray(T[]a)。集合轉成數組時,當指定數組的長度小於集合的長度時,該方法內部會創建一個新的數組,長度是集合的size;相反如果大於集合的長度,則方法中直接使用傳遞進來的數組。我們在使用此方法時,一般設定數組的長度爲集合的長度。爲了限定對元素的操作,無法再進行增刪操作了。使用該方法如下:

                ArrayList<String> al = new ArrayList<String>();
                al.add("abc1");
		al.add("abc2");
		al.add("abc3");
                //將集合轉變爲數組
		String[] arr = al.toArray(new String[al.size()]);
                //再將數組變成字符串
		System.out.println(Arrays.toString(arr));

-------------Java培訓、Android培訓、iOS培訓、.Net培訓、期待與您交流! -------

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