toString()返回该对象的字符串表示。通常,toString 方法会返回一个“以文本方式表示”此对象的字符串。
结果应是一个简明但易于读懂的信息表达式。建议所有Object子类都重写此方法。
因为它是Object里面已经有了的方法,而所有类都是继承Object,所以“所有对象都有这个方法”。
它通常只是为了方便输出,比如System.out.println(xx),括号里面的“xx”如果不是String类型的话,就自动调用xx的toString()方法
总而言之,它只是sun公司开发java的时候为了方便所有类的字符串操作而特意加入的一个方法.
1 package arraySortDemo01; 2 3 class Student implements Comparable<Student>{ 4 private String name; 5 private int age; 6 private float score; 7 public Student(String name,int age,float score){ 8 this.name = name; 9 this.age = age; 10 this.score = score; 11 } 12 public String toString(){ 13 return name + " " + age + " " + score; 14 } 15 public int compareTo(Student stu) { 16 if(this.score >stu.score){ 17 return -1; 18 }else if(this.score < stu.score){ 19 return 1; 20 } else{ 21 if(this.age > stu.age){ 22 return 1; 23 }else if(this.age < stu.age){ 24 return -1; 25 }else{ 26 return 0; 27 } 28 } 29 } 30 } 31 32 public class CompareDemo01 { 33 34 public static void main(String[] args) { 35 Student stu[] = {new Student("zhangsan", 20, 90.0f),new Student("lisi", 18, 80.00f)}; 36 java.util.Arrays.sort(stu); 37 for(int i=0;i<stu.length;i++){ 38 System.out.println(stu[i]); 39 } 40 } 41 }
输出为:
zhangsan 20 90.0
lisi 18 80.0
如果去掉toString()方法:
1 package arraySortDemo01; 2 3 class Student implements Comparable<Student>{ 4 private String name; 5 private int age; 6 private float score; 7 public Student(String name,int age,float score){ 8 this.name = name; 9 this.age = age; 10 this.score = score; 11 } 12 //public String toString(){ 13 // return name + " " + age + " " + score; 14 //} 15 public int compareTo(Student stu) { 16 if(this.score >stu.score){ 17 return -1; 18 }else if(this.score < stu.score){ 19 return 1; 20 } else{ 21 if(this.age > stu.age){ 22 return 1; 23 }else if(this.age < stu.age){ 24 return -1; 25 }else{ 26 return 0; 27 } 28 } 29 } 30 } 31 32 public class CompareDemo01 { 33 34 public static void main(String[] args) { 35 Student stu[] = {new Student("zhangsan", 20, 90.0f),new Student("lisi", 18, 80.00f)}; 36 java.util.Arrays.sort(stu); 37 for(int i=0;i<stu.length;i++){ 38 System.out.println(stu[i]); 39 } 40 } 41 }
输出结果为:
arraySortDemo01.Student@1db9742
arraySortDemo01.Student@106d69c