//第一种 字符串 数组自动排序(sort)
public class test {
public static void main(String[] args) {
String s[]= {"sdfasd","dfddf","sdfsde","jhgfd","esfsfe"};
Comparator comparator = Collator.getInstance(java.util.Locale.CHINA);
Arrays.sort(s,null);
for(String x:s)
System.out.println(s);
}
}
//第一种 汉字数组 排序(Collator)
public class test {
public static void main(String[] args) {
String s[]= {"小强","王刚","李四","张三","王五"};
Comparator comparator = Collator.getInstance(java.util.Locale.CHINA);
Arrays.sort(s,comparator );
for(String x:s)
System.out.println(s);
}
}
//第三种 对象数组按姓名排序 集合中的对象按照姓名排序
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class user3 {
String name;
int age;
public user3(String name,int age) {
this.name=name;
this.age=age;
}
public static void main(String[] args) {
user3 a1=new user3("李王",28);
user3 a2=new user3("苏黄",6);
user3 a3=new user3("张张",39);
user3 a4=new user3("阿方",55);
user3 a5=new user3("阿红",40);
user3 a6=new user3("张毛",29);
user3 s[]={a1,a2,a3,a4,a5,a6}; // 对象数组
//对象数组按姓名排序
// Arrays.sort(s,new Comparator<user3>() {
// Comparator comparator = Collator.getInstance(java.util.Locale.CHINA);
//
// @Override
// public int compare(user3 a, user3 b) {
// //按中文进行排序 需要引用java.text.Collator,且创建对象进行比较
// return comparator.compare(a.name, b.name );
// }
//
// });
// for (user3 o : s) {
// System.out.println(o);
// }
//集合按姓名排序
ArrayList<user3> li=new ArrayList<user3>();
li.add(a1);
li.add(a2);
li.add(a3);
li.add(a4);
li.add(a5);
li.add(a6);
li.sort(new Comparator<user3>() {
@Override
public int compare(user3 a, user3 b) {
//return -(a.getAge()-b.getAge());
//用中文比较器 中的compare直接进行比较
Comparator comparator=Collator.getInstance(java.util.Locale.CHINA);
return comparator.compare(a.getName(),b.getName()) ;
}
});
Iterator it=li.iterator();
while(it.hasNext()) System.out.println(it.next());
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "user3 [name=" + name + ", age=" + age + "]";
}
}