我想写一个类实现 Comparable 比较器 然后 按英文名字 字母大写比较 如abcdef<adcf相同字母 就按下一个字母排序
我直接这样写 不行咯 JAVA中有什么 其他好方法不????知道的讲解下 谢谢哈~~
class MyComparable implements Comparable<MyComparable>{
private String name;
public MyComparable(String name){
this.name=name;
}
public int compareTo(MyComparable temp){
//提示错误 运算符 > 不能应用于 java.lang.String,java.lang.String
return 1;
}
else if(this.name<temp.name){
return -1;
}
else{
return 0;
}
}
}
public class ComparableDemo01{
public static void main(String args[]){
MyComparable[] stu={new MyComparable("jun"),new MyComparable("hua"),
new MyComparable("jing"),new MyComparable("mei"),
new MyComparable("lin"),new MyComparable("bing")};
java.util.Arrays.sort(stu);
}
}
我 用字符串 又可以哦 好奇怪 ~~
String[] stu={"jun","hua","jing","mei","lin","bing"};
java.util.Arrays.sort(stu);
------解决方案--------------------------------------------------------
String[] stu = { "jun", "hua", "jing", "mei", "lin", "bing" };
Arrays.sort(stu, new Comparator<String>() {
public int compare(String arg0, String arg1) {
int result = 0;
int count = 0;
while (true) {
if (arg0.charAt(count) < arg1.charAt(count)) {
result = -1;
break;
} else if (arg0.charAt(count) > arg1.charAt(count)) {
result = 1;
break;
} else {
count++;
if (arg0.length() < count + 1) {
if (arg1.length() >= count + 1) {
result = -1;
break;
}
} else {
if (arg1.length() < count + 1) {
result = 1;
break;
}
}
}
}
return result;
}
});
for (String temp : stu) {
System.out.println(temp);
}
------解决方案--------------------------------------------------------
字符串是不能用>或<比较的,要通过方法来比较
- Java code
public int compareTo(MyComparable temp){if (this.name.compareTo(temp.name) > 0)return 1;}else if(this.name.compareTo(temp.name) < 0){return -1;}else{return 0;}
------解决方案--------------------------------------------------------
class MyComparable implements Comparable<MyComparable>{
private String name;
public String getName() {
return name;
}
public MyComparable(String name){
this.name=name;
}
public int compareTo(MyComparable temp){
return name.compareTo(temp.name);
}
}
public class ComparableDemo01{
public static void main(String args[]){
MyComparable[] stu={new MyComparable("jun"),new MyComparable("hua"),
new MyComparable("jing"),new MyComparable("mei"),
new MyComparable("lin"),new MyComparable("bing")};
java.util.Arrays.sort(stu);
for(int i=0; i<stu.length; ++i){
System.out.println(stu[i].getName());
}
}
}