对象排序

    在javaAPI有个类java.util. Collections。其中有两个方法,分别是:

 

public static <T extends Comparable<? super T>> void sort(List<T> list)

 与

public static <T> void sort(List<T> list, Comparator<? super T> c)

    前者可以对list中的元素进行升序排序,前提是list中的元素必须实现了Comparable接口。可是如果list中的元素没有实现Comparable接口或者想按降序排序的时候,该方法就不够用了,此时我们可以选择第二个方法。

    第二个方法比第一个方法多了一个参数——Comparator类的一个实例对象。通过Comparator的compare方法,我们可以定义自己的比较大小的规则。

    最近公司的一个项目中,从数据库中查询出来的每条记录保存在一个HashMap对象中,然后把所有的HashMap对象保存在一个ArrayList对象中。因为某种原因需要把ArrayList中的HashMap对象根据某个字段的值进行升序排序,可是考虑到HashMap未实现Comparable接口,就只能自己编写一个Comparator对象。详细代码如下:

 

		/*
                 *开始对结果集根据COUNT排序。resultList为一个ArrayList对象,
                 *其中保存有多个HashMap实例,其中每个HashMap实例保存有数
                 *据库查询到的每一条记录,以字段名
                 *作键,字段值做值。
                 */
                if (resultList.size() > 0) {
			Comparator itemComparator = new Comparator() {
				public int compare(Object arg0, Object arg1) {
					HashMap h1 = (HashMap) arg0;
					HashMap h2 = (HashMap) arg1;
					int count1 =
						new Integer(String.valueOf(h1.get("COUNT"))).intValue();
					int count2 =
						new Integer(String.valueOf(h2.get("COUNT"))).intValue();
					return count1 - count2;
				}
			};

			Collections.sort(resultList, itemComparator);
		}
 

你可能感兴趣的:(排序)