问题描述
- 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" 谢谢了
解决方案
/* package whatever; // don't place package name! */
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);
}
}
解决方案二:
[ 2, 5, 7, 8, 10, 15]
解决方案三:
oracle中字符型字段按数字排序
时间: 2025-01-02 09:27:52