本帖最后由 101259@qq.com 于 2012-7-16 11:57 编辑
1、定义一个类,存放汉字和其拼音两个字段,在这个类里面实现Comparable接口,内部按照其拼音比较
2、代码- import java.util.Collections;
- import java.util.LinkedList;
- import java.util.List;
- public class ChineseDemo {
- public static void main(String[] args) {
- List<Chinese>list=new LinkedList<Chinese>();
- Chinese c1=new Chinese("张三","zhangsan");
- Chinese c2=new Chinese("李四","lisi");
- Chinese c3=new Chinese("王五","wangwu");
- list.add(c1);
- list.add(c2);
- list.add(c3);
-
- //①排序前:
- System.out.print("排序前:");
- for(Chinese c:list){
- System.out.print(c.getHanzi()+",");
- }
-
- //对集合排序
- System.out.println();
- System.out.print("排序后:");
-
- Collections.sort(list);
- for(Chinese c:list){
- System.out.print(c.getHanzi()+",");
- }
-
- }
- }
- /*
- * 写一个类,定义两个字段,分别存放汉字和对应的拼音,
- * 并实现Comparable,内部按照他们的拼音比较,
- */
-
- class Chinese implements Comparable<Chinese>{
-
- private String hanzi;
- private String pinyin;
- public Chinese(String hanzi,String pinyin){
- this.hanzi=hanzi;
- this.pinyin=pinyin;
- }
- public String getHanzi() {
- return hanzi;
- }
- public void setHanzi(String hanzi) {
- this.hanzi = hanzi;
- }
- public String getPinyin() {
- return pinyin;
- }
- public void setPinyin(String pinyin) {
- this.pinyin = pinyin;
- }
- //实现compareTo方法,按照Chinese的pinyin比较
- @Override
- public int compareTo(Chinese o) {
- if(this.pinyin.compareTo(o.getPinyin())>0){
- return 1;
- }else if(this.pinyin.compareTo(o.getPinyin())==0){
- return 0;
- }else{
- return -1;
- }
- }
-
- }
复制代码 3、打印结果:可以多添加几个元素,自己试一试
4、我写的代码里面,每次都要将汉字的拼音手动添加进去,你有兴趣的话,看一看pinyin4j.jar 这个开发包,可以通过汉字获取其拼音,就不用每次手工写拼音了
|