簡單排序
阿新 • • 發佈:2020-09-14
1. API設計
類名 | ArrayList |
---|---|
構造方法 | ArrayList():建立ArrayList物件 |
成員方法 | 1. boolean add(E e):向集合中新增元素 2. E remove(int index):從集合中刪除指定的元素 |
2. Comparable介面
需求:
(1)定義一個學生類Student,具有年齡age和姓名username兩個屬性,並通過Comparable介面提供比較規則;
(2)定義測試類Test,在測試類Test中定義測試方法Comparable getMax(Comparable c1,Comparable c2)完成測試。
程式碼:
package sort; //學生類 public class Student implements Comparable<Student>{ private String username; private int age; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Student() { super(); } @Override public String toString() { return "Student{" + "username='" + username + '\'' + ", age=" + age + '}'; } @Override public int compareTo(Student o) { return this.getAge()-o.getAge(); } }
package test; import sort.Student; //測試類 public class Test { public static void main(String[] args) { Student stu1 = new Student(); stu1.setUsername("zhangsan"); stu1.setAge(17); Student stu2 = new Student(); stu2.setUsername("lisi"); stu2.setAge(19); Comparable max = getMax(stu1, stu2); System.out.println(max); } //測試方法,獲取兩個元素中的較大值 public static Comparable getMax(Comparable c1,Comparable c2){ int cmp = c1.compareTo(c2); if (cmp>=0){ return c1; }else{ return c2; } } }
3. 結果