Comparable接口的使用:(知识回顾)
生活随笔
收集整理的這篇文章主要介紹了
Comparable接口的使用:(知识回顾)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Comparable接口的使用:(知識回顧)
1、定義一個學生類,具有年齡age和姓名username兩個屬性,并通過Comparable接口提供比較規則。
package demo02.sort; public class Student implements Comparable<Student>{private String username;private int age;public String getUsername() {return username;}public int getAge() {return age;}public void setUsername(String username) {this.username = username;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Student{" +"username='" + username + '\'' +", age=" + age +'}';}@Overridepublic int compareTo(Student o) {return this.getAge()-o.getAge();} }2、定義測試類TestComparable,在測試類Test中定義測試方法Comparable getMax(comparable c1,comparable c2)完成測試
package demo02.test; import demo02.sort.Student; public class TestComparable {public static void main(String[] args) {Student s1 = new Student();s1.setUsername("張三");s1.setAge(18);Student s2 = new Student();s2.setUsername("李四");s2.setAge(20);Comparable max = getMax(s1, s2);System.out.println(max);}public static Comparable getMax(Comparable c1, Comparable c2) {int result = c1.compareTo(c2);//如果result>0,則c1比c2大,如果result<0,則c2比c1大如果result=0,則c1==c2大if (result >= 0) {return c1;} else {return c2;}} }運行結果:
總結
以上是生活随笔為你收集整理的Comparable接口的使用:(知识回顾)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python的gui界面 可视化_使用可
- 下一篇: mysql 5.7.13 mac_Mac