企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
我们来观察下Arrays类提供的数组排序方法: * 对象数组排序: `public static void sort(Object[] a)` 发现Arrays类里面可以利用sort()方法实现对象数组排序 例子: ~~~ package com.study; import java.util.Arrays; class Book { private String title; private double price; public Book(String title, double price) { this.title = title; this.price = price; } @Override public String toString() { final StringBuilder sb = new StringBuilder("{"); sb.append("\"title\":\"") .append(title).append('\"'); sb.append(",\"price\":") .append(price); sb.append('}'); return sb.toString(); } } public class HelloWorld { public static void main(String[] args) { Book[] books = new Book []{ new Book("java开发", 80), new Book("php", 80), new Book("c++", 80) }; //对象数组排序 Arrays.sort(books); System.out.println(Arrays.toString(books)); } } ~~~ 但是报了个错 ~~~ Exception in thread "main" java.lang.ClassCastException: com.study.Book cannot be cast to java.base/java.lang.Comparable ~~~ 文档中说在数组中的每个元素要实现Comparable这个接口 Comparable接口定义如下 ~~~ public interface Comparable<T> { public int compareTo(T o); } ~~~ 改下 ~~~ package com.study; import java.util.Arrays; class Book implements Comparable<Book>{ private String title; private double price; public Book(String title, double price) { this.title = title; this.price = price; } @Override public String toString() { final StringBuilder sb = new StringBuilder("{"); sb.append("\"title\":\"") .append(title).append('\"'); sb.append(",\"price\":") .append(price); sb.append('}'); return sb.toString(); } @Override public int compareTo(Book o) { //如果传过来的对象大的话就排到后面 // -1表示到后面,1表示排在前面,0表示不动 return (o.price > this.price) ? -1 : 1; } } public class HelloWorld { public static void main(String[] args) { Book[] books = new Book []{ new Book("java开发", 80), new Book("php", 10), new Book("c++", 20) }; Arrays.sort(books); System.out.println(Arrays.toString(books)); } } ~~~