* Collections Demo.
* 1, the tool class for manipulating the collection.
* 2, provides a lot of static methods.
*
* For example , sort the list set, binary search, position substitution.
* Reverse the order of the ordered elements. Reverseorder
* You can also get the maximum and minimum values for the collection.
* The most bull is to turn the Unsynchronized collection into a synchronized set synchronizedxxx
package cn.itcast.p4.collections; import java.util.arraylist;import java.util.collection; import java.util.collections;import java.util.comparator;import java.util.iterator;import java.util.list; import cn.itcast.p2.comparator.comparatorbylength; Public class collectionsdemo { public static void main ( String[] args) { sortdemo (); } &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;//1, demonstrates sorting in collections, sorting elements in a repeating set, Is the method for list. public static void sortdemo () { List<String> list = new ArrayList<String> (); list.add ("abc"); list.add (" Aaaaaaa "); list.add ("Hahah"); list.add ("CBA &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN (list);//list set itself ordered, not sorted //sorting method. //collections.sort (list);//sorted by dictionary order //collections.sort (list,new comparatorbylength ());//Comparator sort, sort by string length //collections.sort (List,collections.reverseorder ());//Sort reversal by dictionary //collections.sort ( List,collections.reverseorder (New comparatorbylength ()));//Reverse the sequencing of existing comparators //String max = collections.max (list);//Get the final value under the natural sort //string max = collections.max (list,new Comparatorbylength ());//Get the bottom row of the comparator in the last value string max = mymax (list);//custom Gets the maximum value in dictionary order, //String max = Mymax (List,new comparatorbylength ());//maximum value obtained by the order of comparators system.out.println ("max=" +max); &NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN (list); } //simulates a Max method. Gets the maximum value in the collection. public static <T extends Object & Comparable<? super t>> t mymax (Collection<? extends t> coll) { iterator<? extends t> it = coll.iterator (); //defines a variable that records a larger value. t max = it.next (); while (It.hasnext ()) { t temp = it.next (); if (Temp.compareto (max) >0) { max = temp; } } return max; } public static String mymax (Collection<string> coll, comparator<string> comp) { iterator<string> it = coll.iterator (); //defines a variable that records a larger value. string max = it.next (); while (It.hasnext ()) { string temp = it.next (); if (Comp.compare (Temp, max) >0) { max = temp; } } return max; } }
Collection Framework Tool Class collections