黑马程序员-JavaAPI-17天-1(Collections-sort)

package string.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/*
 * 集合框架工具类
 * Collections
 * 
 */
public class CollectionsDemo1 {
    public static void main(String[] args) {
        List<String> lists = new ArrayList<String>();
        lists.add("adfgdfgsdf");
        lists.add("dssdsdfs");
        lists.add("bsdfsdf");
        lists.add("zwewsdf");
        System.out.println(lists);
        Collections.sort(lists);
        System.out.println(lists);
        // 根据字符串长度进行排序
        Collections.sort(lists, new StringLengthSort());
        System.out.println(lists);

    }
}

/*
 * 根据字符串长度进行排序
 */
class StringLengthSort implements Comparator<String> {
    @Override
    public int compare(String o1, String o2) {
        int num = new Integer(o1.length()).compareTo(new Integer(o2.length()));
        if (num == 0) {
            return o1.compareTo(o2);
        }
        return num;
    }
}

 

posted @ 2013-03-20 14:32  谷文仁  阅读(157)  评论(0编辑  收藏  举报