Java List collection in a custom sort

/ * 
Set frame tools. 
Collections: Tools collection framework. Inside static methods are defined. 

Collections and Collection What is the difference? 
Collection is a set of interfaces top frame, which defines a common method which separate collection. 
		It has two common sub-interface, 
		List: the elements are defined index. Ordered. Element can be repeated. 
		Set: elements can not be repeated. Disorderly. 

Collections collection framework is a utility class. Methods in this class are static 
		methods provided there are ways to sort the collection list, binary search and so on. 
		Usually common set of threads are unsafe. Because to improve efficiency. 
		If these sets multithreading, may be set by the thread-safe tool class synchronization method, converted into a safe. 
* / 

Import Classes in java.util *;. 

Class the Test3 { 
    public static void main (String [] args) { 
        System.out.println ( "------ ------------- sortDemo --------- "); 
        sortDemo (); 
        System.out.println (" maxDemo ------------- ------------- - "); 
        maxDemo (); 
        / **
         * -------------sortDemo---------------
         * [z, qq, zz, aaa, abcd, kkkkk]
         * -------------maxDemo---------------
         * [aaa, abcd, kkkkk, qq, z, zz]
         * max=zz
         */
    }

    public static void sortDemo() {
        List<String> list = new ArrayList<String>();
        list.add("abcd");
        list.add("aaa");
        list.add("zz");
        list.add("kkkkk");
        list.add("qq");
        list.add("z");
        Collections.sort(list, new StrLenComparator());
        sop(list);
    }

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

        list.add("abcd");
        list.add("aaa");
        list.add("zz");
        list.add("kkkkk");
        list.add("qq");
        list.add("z");
        Collections.sort(list);
        sop(list);
        String max = Collections.max(list);
        sop("max=" + max);
    }

    public static void sop(Object obj) {
        System.out.println(obj);
    }
}


/**
 * 比较器,先按字符长度然后按自然排序
 */
class StrLenComparator implements Comparator<String> {
    public int compare(String s1, String s2) {
        if (s1.length() > s2.length())
            return 1;
        if (s1.length() < s2.length())
            return -1;
        return s1.compareTo(s2);
    }
}

  

Guess you like

Origin www.cnblogs.com/smartsmile/p/11616224.html