|
我们看到了这个就能知道了,在中文是怎么样用list来排序,我们先来看看代码,这样的话大家理解的也比较好,要是我哪的解析不对,也不用把大家的思路给整错了。下面就是代码:
java代码:[li]import java.text.Collator;[/li][li]import java.util.ArrayList;[/li][li]import java.util.Collections;[/li][li]import java.util.Comparator;[/li][li]import java.util.Iterator;[/li][li][/li][li]public class ChineseCharacterSortDemo {[/li][li][/li][li]public static void main(String args[]) {[/li][li][/li][li]ArrayList list = new ArrayList();[/li][li][/li][li]list.add(new Country(86, "中国"));[/li][li][/li][li]list.add(new Country(21, "加拿大"));[/li][li][/li][li]list.add(new Country(1, "美国"));[/li][li][/li][li]list.add(new Country(110, "阿富汗"));[/li][li][/li][li]Comparator cmp = new ChinsesCharComp();[/li][li][/li][li]Collections.sort(list, cmp);[/li][li][/li][li]Iterator iter = list.iterator();[/li][li][/li][li]while (iter.hasNext()) {[/li][li][/li][li]Country s1 = (Country) iter.next();[/li][li][/li][li]System.out.println(s1.getCode() + "----" + s1.getName());[/li][li][/li][li]}[/li][li][/li][li]}[/li][li][/li][li]}[/li][li][/li][li]class ChinsesCharComp implements Comparator {[/li][li][/li][li]public int compare(Object o1, Object o2) {[/li][li][/li][li]Country c1 = (Country) o1;[/li][li][/li][li]Country c2 = (Country) o2;[/li][li][/li][li]Collator myCollator = Collator.getInstance(java.util.Locale.CHINA);[/li][li][/li][li]if (myCollator.compare(c1.getName(), c2.getName()) < 0)[/li][li][/li][li]return -1;[/li][li][/li][li]else if (myCollator.compare(c1.getName(), c2.getName()) > 0)[/li][li][/li][li]return 1;[/li][li][/li][li]else[/li][li][/li][li]return 0;[/li][li][/li][li]}[/li][li][/li][li]}[/li][li][/li][li]class Country {[/li][li][/li][li]private long code;[/li][li][/li][li]private String name;[/li][li][/li][li]public long getCode() {[/li][li][/li][li]return code;[/li][li][/li][li]}[/li][li][/li][li]public void setCode(long code) {[/li][li][/li][li]this.code = code;[/li][li][/li][li]}[/li][li][/li][li]public String getName() {[/li][li][/li][li]return name;[/li][li][/li][li]}[/li][li][/li][li]public void setName(String name) {[/li][li][/li][li]this.name = name;[/li][li][/li][li]}[/li][li][/li][li]public Country() {[/li][li][/li][li]}[/li][li][/li][li]public Country(long code, String name) {[/li][li][/li][li]this.code = code;[/li][li][/li][li]this.name = name;[/li][li][/li][li]}[/li][li][/li][li]}
[/li]
复制代码
大家看了代码以后,我们就开始说说吧,我们最先得new一个ArrayList();,这个完事以后,我们先来写一个while 循环,循环的条件是(iter.hasNext()) ,这样我们最后就是判断,判断的条件是myCollator.compare(c1.getName(), c2.getName()) < 0。大家要记住的是,我们返回的值一定要写对,而不是True和false。我说的话大家可要放在心上哦 |
|