http://blog.sina.com.cn/s/blog_81a9aa7e0100tizj.html
在java或者是android编程的时候,我们经常要用到对姓名或者其他字符串排序,现在我写写自己曾经做过的列子。
普通的数组字符串排序,通过构造器来实现:
假如在main方法中有String name[5] = {"one","张三","李四","王五","two"};
只要调用Arrays.sort(name,0,5,new Comparents());就可以了。
importjava.text.Collator;importjava.util.Comparator;importjava.util.Locale;public class Comparents implements Comparator{
@Overridepublic intcompare(Object arg0, Object arg1) {
String one=(String)arg0;
String two=(String)arg1;
Collator ca=Collator.getInstance(Locale.CHINA);int flags = 0;if (ca.compare(one,two) < 0) {
flags= -1;
}else if(ca.compare(one,two) > 0) {
flags= 1;
}else{
flags= 0;
}returnflags;
}
}
在android中,我们经常要用到HashMap,经常用list存放HashMap,我们对List中的元素进行排序的时候,就要用到构造器了,下面具体用列子说说:
假如在main方法中有:
public List> listitem;
listitem.add(new HashMap("name","one"));
listitem.add(new HashMap("name","张三"));
listitem.add(new HashMap("name","李四"));
listitem.add(new HashMap("name","王五"));
listitem.add(new HashMap("name","two"));
Comparent comparent = new Comparent();
Collections.sort(listitem, comparent);
其中在Comparent.java文件中定义方法如下:
importjava.text.Collator;importjava.util.Comparator;importjava.util.HashMap;importjava.util.Locale;public class Comparent implements Comparator{
@SuppressWarnings("unchecked")
@Overridepublic intcompare(Object arg0, Object arg1) {
HashMap name1 = (HashMap)arg0;
HashMap name2 = (HashMap)arg1;
Collator ca=Collator.getInstance(Locale.CHINA);int flags = 0;if (ca.compare((String) name1.get("name"), (String)name2.get("name")) < 0) {
flags= -1;
}else if(ca.compare((String) name1.get("name"), (String)name2.get("name")) > 0) {
flags= 1;
}else{
flags= 0;
}returnflags;
}
}