目录
481-Arrays排序源码解读
接口编程-compare
483-Arrays模拟排序
484-Arrays其他方法
二分搜索查找要求有序,如果数组中不存在这个元素,返回-(low+1)
使用int就是0,Integer就会是null
如果拷贝长度<0就抛出异常NegativeArraySizeException
485-Arrays课堂练习
package chapter13.arrays;
import java.util.Arrays;
import java.util.Comparator;
/**
* @author LuHan
* @version 1.0
*/
public class ArraysExcercise {
public static void main(String[] args) {
Book[] books = new Book[4];
books[0]= new Book("红楼梦~", 100);
books[1]= new Book("金瓶梅~",90);
books[2] = new Book("青年文摘", 5);
books[3]= new Book("java从入门到放弃", 300);
Arrays.sort(books, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Book book1=(Book) o1;
Book book2=(Book) o2;
double priceVal= book2.getPrice()-book1.getPrice();
if(priceVal>0){
return 1;
}else if(priceVal<0){
return -1;
}else {
return 0;
}
}
});
System.out.println(Arrays.toString(books));
}
}
class Book{
private String name;
private double price;
public Book(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}