怎么使用微wordpress百度优化大师
String类型的compareTo方法:
在String引用中,有一个方法可以比较两个字符串的大小:
和C语言中是一样的,两个字符串一个字符一个去比较。
那么这个方法是怎么实现的呢?
其实就是一个接口:Comparable接口里面的compareTo方法。
也就是如果能扩展这个接口,然后重写这个方法我们也可以在不同的类中实现自己想实现的方法。
比较两个学生年龄大小:
@Overridepublic int compareTo(Object o) {Student student = (Student) o;return this.age- student.age;}
比较两个学生名字长短:
//比较两个学生名字大小:@Overridepublic int compareTo(Object o) {Student student = (Student) o;return this.name.compareTo(student.name);}
在main方法中测试:
用名字比较:
public static void main(String[] args) {Student student1 = new Student(13,"zhangsan");Student student2 = new Student(15,"lisi");if(student1.compareTo(student2)>0){System.out.println("student1>student2");}else{System.out.println("student1<=student2");}}
用年龄比较:
两个结果是不一样的。
自写排序方法:
我们可以借助该方法写一个排序方法:
public static void mySort(Comparable[] comparables) {for (int i = 0; i < comparables.length - 1; i++) {for (int j = 0; j < comparables.length - 1 - i; j++) {//if(comparables[j] > comparables[j+1]) {if (comparables[j].compareTo(comparables[j + 1]) > 0) {//交换Comparable tmp = comparables[j];comparables[j] = comparables[j + 1];comparables[j + 1] = tmp;}}}}
用多态写是比较合理的!
当然也可以不用多态:
@Overridepublic int compareTo(Object o) {Student student = (Student) o;return this.name.compareTo(student.name);}public static void mySort(Student[] students){for(int i = 0;i<students.length-1;i++) {for (int j = 0; j <students.length-i-1; j++) {if(students[j].compareTo(students[j+1])>0){Student tmp = students[j];students[j] = students[j+1];students[j+1] = tmp;}}}}
建议用多态!!