java对象排序

Java集合对象排序测试

 
Java API针对集合类型排序提供了两种支持:
java.util.Collections.sort(java.util.List)
java.util.Collections.sort(java.util.List, java.util.Comparator)
 
第一个方法要求所排序的元素类必须实现java.lang.Comparable接口。
第二个方法要求实现一个java.util.Comparator接口。
 
java.lang.Comparable接口和java.util.Comparator接口是Java对排序最提供最基本支持。这两个接口不但可以用于集合元素排序,还可以用于数组排序。
 
如果数组或集合元素是String类型,则可以利用Java API实现的Comparator<String>对象String.CASE_INSENSITIVE_ORDER为容器元素排序。
 
下面给出两个里测试,涵盖集合和数组的排序,并且还演示了数组和集合的相互转换:
 
例子一:实现Comparable接口排序
 
package collsort.comparable;

/**
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2008-3-29 22:21:19
* Company: LavaSoft(
http://lavasoft.blog.51cto.com )
* 要排序的元素对象
*/
public class Cat implements Comparable<Cat> {
    private int age;
    private String name;

    public Cat(int age, String name) {
        this .age = age;
        this .name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this .age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this .name = name;
    }


    public String toString() {
        return "Cat{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    public int compareTo(Cat o) {
        return this .getAge() - o.getAge();
    }
}

 
package collsort.comparable;

import java.util.*;

/**
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2008-3-29 22:24:12
* Company: LavaSoft(
http://lavasoft.blog.51cto.com )
* 通过实现Comparable接口实现个性化排序测试
*/
public class TestComparable {

    public static String outCollection(Collection coll) {
        StringBuffer sb = new StringBuffer();
        for (Object obj : coll) {
            sb.append(obj + "\n" );
        }
        System.out.println(sb.toString());
        return sb.toString();
    }

    public static void main(String args[]) {
        test();
        test2();
    }

    public static void test() {
        System.out.println("----------test()---------" );
        System.out.println("升序排序测试:" );
        List<Cat> listCat = new ArrayList<Cat>();
        Cat cat1 = new Cat(34, "hehe" );
        Cat cat2 = new Cat(12, "haha" );
//        Person catx = new Person(12, "lavasoft");
        Cat cat3 = new Cat(23, "leizhimin" );
        Cat cat4 = new Cat(13, "lavasoft" );

        listCat.add(cat1);
        listCat.add(cat2);
        listCat.add(cat3);
//        listCat.add(catx);

        System.out.println("原集合为:" );
        outCollection(listCat);

        System.out.println("调用Collections.sort(List<T> list)排序:" );
        Collections.sort(listCat);
        outCollection(listCat);
        
        System.out.println("逆序排列元素:" );
        Collections.sort(listCat, Collections.reverseOrder());
        outCollection(listCat);

        System.out.println("再次逆序排列元素:" );
        Collections.reverse(listCat);
        outCollection(listCat);

        System.out.println("添加一个元素后输出集合:" );
        listCat.add(cat4);
        outCollection(listCat);

        System.out.println("排列后输出:" );
        Collections.sort(listCat);
        outCollection(listCat);
    }

    /**
     * 针对数组的排序
     */
    public static void test2(){
        String[] strArray = new String[] {"z" , "a" , "C" };
        System.out.println("-------------数组转换为列表-------------" );
        List<String> list = Arrays.asList(strArray);
        outCollection(list);

        System.out.println("-------------列表转换为数组(1)-------------" );
        String[] strArrayNew1 = list.toArray(strArray);
        for (String str:strArrayNew1){
            System.out.println(str);
        }
        System.out.println("-------------列表转换为数组(2)-------------" );
        String[] strArrayNew2 = (String[]) list.toArray();
        for (String str:strArrayNew2){
            System.out.println(str);
        }

        System.out.println("-------------顺序排序列表-------------" );
        Collections.sort(list);
        outCollection(list);

        System.out.println("-----按String实现的Comparator对象String.CASE_INSENSITIVE_ORDER排序----" );
        Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
        outCollection(list);

        System.out.println("-------------倒序排序列表-------------" );
        Collections.sort(list, Collections.reverseOrder());
        outCollection(list);

        System.out.println("-----按String实现的Comparator对象String.CASE_INSENSITIVE_ORDER排序----" );
        Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
        outCollection(list);

        System.out.println("-----反转列表元素的顺序------" );
        Collections.reverse(list);
        outCollection(list);
    }
}

 运行结果:
----------test()---------
升序排序测试:
原集合为:
Cat{age=34, name='hehe'}
Cat{age=12, name='haha'}
Cat{age=23, name='leizhimin'}

调用Collections.sort(List<T> list)排序:
Cat{age=12, name='haha'}
Cat{age=23, name='leizhimin'}
Cat{age=34, name='hehe'}

逆序排列元素:
Cat{age=34, name='hehe'}
Cat{age=23, name='leizhimin'}
Cat{age=12, name='haha'}

再次逆序排列元素:
Cat{age=12, name='haha'}
Cat{age=23, name='leizhimin'}
Cat{age=34, name='hehe'}

添加一个元素后输出集合:
Cat{age=12, name='haha'}
Cat{age=23, name='leizhimin'}
Cat{age=34, name='hehe'}
Cat{age=13, name='lavasoft'}

排列后输出:
Cat{age=12, name='haha'}
Cat{age=13, name='lavasoft'}
Cat{age=23, name='leizhimin'}
Cat{age=34, name='hehe'}

-------------数组转换为列表-------------
z
a
C

-------------列表转换为数组(1)-------------
z
a
C
-------------列表转换为数组(2)-------------
z
a
C
-------------顺序排序列表-------------
C
a
z

-----按String实现的Comparator对象String.CASE_INSENSITIVE_ORDER排序----
a
C
z

-------------倒序排序列表-------------
z
a
C

-----按String实现的Comparator对象String.CASE_INSENSITIVE_ORDER排序----
a
C
z

-----反转列表元素的顺序------
z
C
a


Process finished with exit code 0

 
例子一:实现Comparator接口排序
package collsort.compare;

/**
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2008-3-29 13:28:29
* Company: LavaSoft(
http://lavasoft.blog.51cto.com )
* 要排序的元素对象
*/
public class Person {
    private int age;
    private String name;

    public Person(int age, String name) {
        this .age = age;
        this .name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this .age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this .name = name;
    }

    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}
 
package collsort.compare;

import java.util.Comparator;

/**
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2008-3-29 13:29:35
* Company: LavaSoft(
http://lavasoft.blog.51cto.com )
* Person类的排序接口
*/
public class PersonComparator implements Comparator<Person> {
    /**
     * 排序接口算法实现
     *
     * @param o1
     * @param o2
     * @return 比较结果的大小
     */
    public int compare(Person o1, Person o2) {
        return o1.getAge() - o2.getAge();
    }
}
 
package collsort.compare;

import collsort.compare.Person;

import java.util.*;

/**
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2008-3-29 13:30:49
* Company: LavaSoft(
http://lavasoft.blog.51cto.com )
* 通过Comparator接口实现个性化排序测试
* 结论:Comparator接口是一个为集合对象排序的基本算法,其中的compare方法是比较两个元素对象的比较方式.Java Collection框架利用这个算法实现了不同集合类型对象排序方式的统一.<br>
* 排序针对的是确切的集合对象,当集合对象的元素发生变化时,集合内的元素不会自动重新排序.
*/
public class TestComparator {
    public static String outCollection(Collection coll) {
        StringBuffer sb = new StringBuffer();
        for (Object obj : coll) {
            sb.append(obj + "\n" );
        }
        System.out.println(sb.toString());
        return sb.toString();
    }

    public static void main(String args[]) {
        test1();
    }

    public static void test1() {
        System.out.println("----------test1()---------" );
        System.out.println("升序排序测试:" );
        List<Person> listPerson = new ArrayList<Person>();
        Person person1 = new Person(34, "lavasoft" );
        Person person2 = new Person(12, "lavasoft" );
//        Person personx = new Person(12, "lavasoft");
        Person person3 = new Person(23, "leizhimin" );
        Person person4 = new Person(13, "sdg" );

        listPerson.add(person1);
        listPerson.add(person2);
        listPerson.add(person3);
//        listPerson.add(personx);

        Comparator<Person> ascComparator = new PersonComparator();

        System.out.println("原集合为:" );
        outCollection(listPerson);

        System.out.println("排序后集合为:" );
        //利用Collections类静态工具方法对集合List进行排序
        Collections.sort(listPerson, ascComparator);
        outCollection(listPerson);

        System.out.println("在继续添加一个Person对象,集合为:" );
        listPerson.add(person4);
        outCollection(listPerson);

        System.out.println("添加一个对象后,重新排序输出:" );
        Collections.sort(listPerson, ascComparator);
        outCollection(listPerson);

        System.out.println("\n降序排序测试:" );
        //从升序排序对象产生一个反转(降序)的排序对象
        Comparator<Person> descComparator = Collections.reverseOrder(ascComparator);
        System.out.println("利用反转后的排序接口对象对集合List排序并输出:" );
        Collections.sort(listPerson, descComparator);
        outCollection(listPerson);

        System.out.println("\n求最大最小元素测试:" );
        Person p_max = Collections.max(listPerson, ascComparator);
        Person p_min = Collections.min(listPerson, ascComparator);
        System.out.println("最大元素为:" + p_max.toString());
        System.out.println("最小元素为:" + p_min.toString());
    }
}
 
运行结果:
----------test1()---------
升序排序测试:
原集合为:
Person{age=34, name='lavasoft'}
Person{age=12, name='lavasoft'}
Person{age=23, name='leizhimin'}

排序后集合为:
Person{age=12, name='lavasoft'}
Person{age=23, name='leizhimin'}
Person{age=34, name='lavasoft'}

在继续添加一个Person对象,集合为:
Person{age=12, name='lavasoft'}
Person{age=23, name='leizhimin'}
Person{age=34, name='lavasoft'}
Person{age=13, name='sdg'}

添加一个对象后,重新排序输出:
Person{age=12, name='lavasoft'}
Person{age=13, name='sdg'}
Person{age=23, name='leizhimin'}
Person{age=34, name='lavasoft'}


降序排序测试:
利用反转后的排序接口对象对集合List排序并输出:
Person{age=34, name='lavasoft'}
Person{age=23, name='leizhimin'}
Person{age=13, name='sdg'}
Person{age=12, name='lavasoft'}


求最大最小元素测试:
最大元素为:Person{age=34, name='lavasoft'}
最小元素为:Person{age=12, name='lavasoft'}

Process finished with exit code 0

 
 
最后说明一下,Java如何通过所实现接口的方法进行排序是API内部的事情,Java这样处理排序目的就是对容器元素排序有一个统一的方式,以简化编程。
 
当然也可以自己通过别的算法进行元素排序,在此不做讨论。


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/woshiliukui/archive/2009/07/27/4382866.aspx

你可能感兴趣的:(java,C++,c,算法,idea)