现有若干字符串:123,201,300,899,722,429,9,65...现在要求以5开头的字符串在排序时放在第一位,然后以4开头、3开头、2开头、1开头,然后再按正常的6、7、8、9顺序排序剩下的字符串。因此上面的字符串排序后应该是这样的:
429,300,201,123,65,722,899,9
我写了一个继承Comparator类然后重写compare()
if(str.startsWith(""5)){
return -1;
}else if(str.startsWith("4")){
return -1
}.....
可是不行请大侠们提供下思路!
429,300,201,123,65,722,899,9
我写了一个继承Comparator类然后重写compare()
if(str.startsWith(""5)){
return -1;
}else if(str.startsWith("4")){
return -1
}.....
可是不行请大侠们提供下思路!
private String num;
public DiyString(String num) {
this.num = num;
} @Override
public int compareTo(Object o) {
String onum = ((DiyString)o).num;
char first = num.charAt(0);
char ofirst = onum.charAt(0);
if (first == ofirst) {
return num.compareTo(onum);
} else if (first <= '5' && first >= '1') {
if (ofirst <= '5' && ofirst >= '1') {
if (first > ofirst) {
return -1;
} else {
return 1;
}
} else {
return -1;
}
} else if (first <= '9' && first >= '6') {
if (ofirst <= '9' && ofirst >= '6') {
if (first > ofirst) {
return 1;
} else {
return -1;
}
} else {
return 1;
}
} else {
return num.compareTo(onum);
}
}
public String toString() {
return num;
}
public static void main(String[] args) {
DiyString[] nums = new DiyString[8];
nums[0] = new DiyString("123");
nums[1] = new DiyString("201");
nums[2] = new DiyString("300");
nums[3] = new DiyString("899");
nums[4] = new DiyString("722");
nums[5] = new DiyString("429");
nums[6] = new DiyString("9");
nums[7] = new DiyString("65");
Arrays.sort(nums);
for (DiyString num : nums) {
System.out.println(num);
}
}
}
这样用简单点
public static void main(String[] args) {
String[] datas = {"123", "201", "300", "899", "722", "429", "9", "65"};
DiyString[] nums = new DiyString[datas.length];
for (int i=0;i<nums.length;i++) {
nums[i] = new DiyString(datas[i]);
}
Arrays.sort(nums);
for (DiyString num : nums) {
System.out.println(num);
}
}
list.add("123");
list.add("234");
list.add("34");
list.add("32");
list.add("565");
list.add("76");
list.add("1246");
list.add("909"); Collections.sort(list);
Collections.reverse(list);
System.out.println(list);
String x = i+“”;
...循环取出str;
if(str.startsWith("i"))
{
把Str放到另一个字符数组Str2里
}
}这样在 Str2里就是 5~1排好的没在str2里面的 就是另外排的
给你写一个,自己参考改吧
public int compare(String o1, String o2) {
if (o1 == null) {
return ((o2==null) ? 0 : 1);
} else if (o2 == null) {
return -1;
} else if (o1.length() == 0) {
return ((o2.length()==0) ? 0 : 1);
} else if (o2.length() == 0) {
return -1;
} else if (o1.substring(0,1).equals(o2.substring(0,1))) {
return o1.compareTo(o2);
} else if (o1.substring(0, 1).compareTo("5") <= 0) {
if (o2.substring(0, 1).compareTo("5") > 0) {
v = -1;
} else {
return o2.substring(0, 1).compareTo(o1.substring(0, 1));
}
} else if (o1.substring(0, 1).compareTo("5") > 0) {
if (o2.substring(0, 1).compareTo("5") <= 0) {
return 1;
} else {
return o1.substring(0, 1).compareTo(o2.substring(0, 1));
}
}
return 0;
}