用法是:spring
List<Book> list_book = new ArrayList<Book>(); Book book=new Book(1,"aa","a",2,1); Book book1=new Book(2,"bb","b",2,1); Book book2=new Book(3,"cc","c",2,1); list_book.add(book2); list_book.add(book1); list_book.add(book); Collections.sort(list_book); for (Book book3 : list_book) { System.out.println(book3); }
Book類要實現:Comparable接口 重寫compareTo()方法springboot
package com.springboot_thread.bean; import lombok.Data; import lombok.Getter; import lombok.Setter; /** * 做用: */ @Data public class Book implements Comparable<Book>{ private Integer id; private String bookName; private String author; private Integer stock; private Integer tId; public Book() { } public Book(Integer id, String bookName, String author, Integer stock, Integer tId) { this.id = id; this.bookName = bookName; this.author = author; this.stock = stock; this.tId = tId; } @Override public int compareTo(Book o) { return this.id-o.id; //升序 //return o.id-this.id; 降序 } }