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);
}
}