類集演算法 Collections.reverseOrder() 、 Comparator 、 shuffle()

來源:互聯網
上載者:User

/*

該程式建立和初始化了一個鏈表。reverseOrder()方法返回一個對Integer對象的比較進行逆向的Comparator函數。列表中元素按照這個比較函數進行排序並被顯示出來。接下來,調用shuffle()方法對列表進行隨機排列,然後顯示列表的最大值和最小值。

*/

//Demonstrate various algorithms.
import java.util.*;
class  AlgorithmDemo{
 public static void main(String[] args)
 {
  //Create and initialize linked list.
  LinkedList ll = new LinkedList();
  ll.add(new Integer(-9));
  ll.add(new Integer(10));
  ll.add(new Integer(-10));
  ll.add(new Integer(9));
  ll.add(new Integer(99));
  ll.add(new Integer(100));

  //Create a reverse order comparator.
  Comparator r = Collections.reverseOrder();

  //Sort list by using the comparator.
  Collections.sort(ll,r);

  //Get an iterator.
  Iterator i = ll.iterator();

  System.out.println("List sorted in reverse: ");
  while(i.hasNext()){
   System.out.println(i.next() + " ");
  }
  System.out.println();
  Collections.shuffle(ll);

  //Display randomized list
  i = ll.iterator();
  System.out.print("List shuffled: ");
  while(i.hasNext()){
   System.out.print(i.next() + " ");
  }
  System.out.println();

  System.out.println("Minimum: " + Collections.min(ll));
  System.out.println("Maximum: " + Collections.max(ll));
 }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.