开发者社区> 问答> 正文

Java中用TreeSet方法排序字符型数字怎么排序

public class Demo implements Comparable{
//String str;
String str;
/*public Demo(){
}*/
public Demo(String str){
    this.str=str;
}
public void getStr(String str){
    this.str=str;
}
public String setStr(){
    return str;
}
//重写toString()方法
public String toString(){
    return  " "+this.str;
}
//比较规则
public int compareTo(Object arg0) {
    return 1;
}
}
public class SortByNum implements Comparator{
public int compare(Object arg0, Object arg1) {
    Demo d1=(Demo)arg0;
    Demo d2=(Demo)arg1;
    int temp = 0;
    String str1=d1.toString();//转换成字符串
    String str2=d2.toString();//转换成字符串
    char[] ch1=str1.toCharArray();//转换成数组
    char[] ch2=str2.toCharArray();//转换成数组
    for(int i=0;i<ch1.length;i++){
        for(int j=0;j<ch2.length;j++){
            temp=d1.compareTo(d2);
        }
    }
    //int temp=d1.compareTo(d2);
    return  temp;
}
}
public class TreeSets {
public static void main(String[] args) {
//Demo demo=new Demo();
//创建一个TreeSet集合
TreeSet tree=new TreeSet(new SortByNum());
//添加字符
tree.add(new Demo("15"));
tree.add(new Demo("19"));
tree.add(new Demo("16"));
tree.add(new Demo("99"));
System.out.println(tree);
}
}

麻烦大家看一下,就是不知道怎么做,例如:String str="8 10 15 2 5 7";输出"2 5 7 8 10 15"

展开
收起
蛮大人123 2016-06-08 16:03:23 4273 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    
    class Demo implements Comparable{
        String str;
    
        public Demo(String str){
            this.str=str;
        }
        public void setStr(String str){
            this.str=str;
        }
        public String getStr(){
            return str;
        }
        //重写toString()方法
        public String toString(){
            return  " "+this.str;
        }
        //比较规则
        public int compareTo(Object arg0) {
            Demo d2 = (Demo)arg0;
            if (d2.getStr().length() != str.length()) return str.length() - d2.getStr().length();
            return str.compareTo(d2.getStr());
        }
    }
    
    class SortByNum implements Comparator{
    
        public int compare(Object arg0, Object arg1) {
            Demo d1=(Demo)arg0;
            Demo d2=(Demo)arg1;
            return d1.compareTo(d2);
        }
    }
    
    /* Name of the class has to be "Main" only if the class is public. */
    class Ideone
    {
        public static void main (String[] args) throws java.lang.Exception
        {
            // your code goes here
            //创建一个TreeSet集合
            TreeSet tree=new TreeSet(new SortByNum());
            //添加字符
            String s = "8 10 15 2 5 7";
            for (String s1 : s.split(" "))
                tree.add(new Demo(s1));
            System.out.println(tree);
        }
    }
    2019-07-17 19:32:11
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载