java中Collection和collections的區別

來源:互聯網
上載者:User

標籤:tree   cto   測試   遊戲   工具   pre   演算法   linked   統一   

1、Collection是java.util中的一介面,他提供了對集合對象進行基本操作的通用介面方法。Collection介面在java類庫中有很多具體的實現。Collection介面的意義是為各種具體的集合提供了最大化的統一操作方式,其直接繼承介面LIst與Set。

Collection(

List(LinkedLIst,ArrayList,Vector),

set(hashSet,treeSet)

)

2、Collection則是集合類的一個工具類或者是協助類,提供給了一系列的靜態方法,用於對集合中元素進行排列、搜尋以及安全執行緒等各種操作。

1)排序(sort)

  使用sort方法可以根據元素的自然順序,對指定列表按升序進行排序。列表中的所有元素必須實現Comparable介面。此列表內的所有元素都必須是使用指定比較子互相比較的。

List<Integer> list = new ArrayList<Integer>();        int array[] = {112, 111, 23, 456, 231 };        for (int i = 0; i < array.length; i++) {            list.add(array[i]);        }        Collections.sort(list);        for (int i = 0; i < array.length; i++) {            System.out.println(list.get(i));        }

 2)複製(copy)

          //定義一個listList<Integer> list=new ArrayList<Integer>();Integer math[]={23,34,432,23,43,12,23,32};for(int i=0;i<math.length;i++){list.add(math[i]);}//新的listList<Integer> lists=new ArrayList<Integer>(Arrays.asList(new Integer[list.size()]));System.out.println(list);//copy(被賦值的在前,是在後)Collections.copy(lists,list);System.out.println(lists.size());for (Integer integer : lists) {System.out.print(integer+",");}

  3)混排(Shuffling)

混排演算法所做的正好與 sort 相反: 它打亂在一個 List 中可能有的任何排列的蹤跡。也就是說,基於隨機源的輸入重排該 List, 這樣的排列具有相同的可能性(假設隨機源是公正的)。這個演算法在實現一個碰運氣的遊戲中是非常有用的。例如,它可被用來混排代表一副牌的 Card 對象的一個 List 。另外,在產生測試案例時,它也是十分有用的。

Collections.Shuffling(list)

  4)反轉(Reverse)
使用Reverse方法可以根據元素的自然順序 對指定列表按降序進行排序。
Collections.reverse(list)

  5)替換所以的元素(Fill)

使用指定元素替換指定列表中的所有元素。

Collections.fill(li,"aaa");

  6)返回Collections中最小元素(min)
根據指定比較子產生的順序,返回給定 collection 的最小元素。collection 中的所有元素都必須是通過指定比較子可相互比較的
Collections.min(list)

  7)返回Collections中最大元素(max)
根據指定比較子產生的順序,返回給定 collection 的最大元素。collection 中的所有元素都必須是通過指定比較子可相互比較的
Collections.max(list)

  8) lastIndexOfSubList
返回指定源列表中最後一次出現指定目標列表的起始位置
int count = Collections.lastIndexOfSubList(list,li);

  9) IndexOfSubList
返回指定源列表中第一次出現指定目標列表的起始位置
int count = Collections.indexOfSubList(list,li);

  10) Rotate
根據指定的距離迴圈移動指定列表中的元素
Collections.rotate(list,-1);
如果是負數,則正向移動,正數則方向移動

java中Collection和collections的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.