Java在Objecj要排序的必須自己去實作compareTo的方法

而使用上還是Arrays.sort和Collections.sort

以下簡單介紹用法

 

1. 創例一個class, 設定package, 設定屬性和建構子

public class Student{
 private int id;
 private String name;

 Student(int id, String name){
  this.id = id;
  this.name = name;
 }
 
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
}

01.png

 

2. 實作Comparable, 然後實作compareTo的方法

這邊根據要續的相目來修改

精神如下

 @Override
 public int compareTo(Student student) {
  int compareQuantity = student.getId();
  //ascending order
  return this.id - compareQuantity;
  //descending order
//  return compareQuantity - this.id;
 }

02.png

 

3. 然後回到主程式, 呼叫Arrays.sort或Collections.sort來排序

這邊是List所以用Collections.sort來排序

package example;

import java.util.ArrayList;
import java.util.Collections;

public class Sort {
 public static void main(String args[]) {
  ArrayList<Student> arrayStudent = new ArrayList<>();
  arrayStudent.add(new Student(4,"John"));
  arrayStudent.add(new Student(3,"Bill"));
  arrayStudent.add(new Student(1,"Linda"));
  arrayStudent.add(new Student(2,"Marry"));
  
  Collections.sort(arrayStudent);
  
  for(Student temp: arrayStudent){
     System.out.println("id : " + temp.getId() +
   ", nmae : " + temp.getName());
  }
  
 }
}

03.png

 

4. 最後可以靠到ArrayList內的Object依照id做排序

04.png  

arrow
arrow
    文章標籤
    Java Object Sort compareTo
    全站熱搜

    RX1226 發表在 痞客邦 留言(0) 人氣()