- package lession;
-
- import java.io.UnsupportedEncodingException;
- import java.text.Collator;
- import java.util.Comparator;
- import java.util.List;
- import java.util.ArrayList;
- import java.util.Collections;
-
- class User {
- String name;
- int age;
-
- public User(String name,int age){
- this.name=name;
- this.age=age;
- }
- 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;
- }
- }
-
- class ComparatorUser implements Comparator{
- Collator collator = Collator.getInstance(java.util.Locale.CHINA);
- public int compare(Object arg0, Object arg1) {
- User user0=(User)arg0;
- User user1=(User)arg1;
- String name0=toUTF_8(user0.getName());
- String name1=toUTF_8(user1.getName());
- int age0=user0.getAge();
- int age1=user1.getAge();
-
- int flag=collator.getCollationKey(name0).compareTo(collator.getCollationKey(name1));
- if(flag==0){
- return Integer.valueOf(age0).compareTo(Integer.valueOf(age1));
- }else{
- return flag;
- }
- }
- private static String toUTF_8(String str) {
- try {
- return new String(str.getBytes(), "ISO-8859-1");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- throw new RuntimeException(e);
- }
- }
- }
-
- public class SortTest {
-
-
- public static void main(String[] args){
- List userlist=new ArrayList();
- userlist.add(new User("吉斌",4));
- userlist.add(new User("何佳",1));
- userlist.add(new User("張哲",5));
- userlist.add(new User("段建波",6));
- userlist.add(new User("鄧斯奇",5));
- userlist.add(new User("鄧斯奇",3));
-
- ComparatorUser comparator=new ComparatorUser();
- Collections.sort(userlist, comparator);
-
- for (int i=0;i<userlist.size();i++){
- User user_temp=(User)userlist.get(i);
- System.out.println(user_temp.getName()+","+user_temp.getAge());
- }
-
- }
- }
上面的程序?qū)崿F(xiàn)了,對中文的排序。
默認(rèn)是根據(jù)字符串的ASCII/Unicode的編碼排序的,若想按照漢字的拼音排序,需要把字符串轉(zhuǎn)換編碼為iso-8859-1.
如果你的文本是本地語言,而不是缺省語言,你需要傳遞一個(gè)本地語種給getInstance()方法
|