欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java 挽救的比较器(Comparator)

程序员文章站 2022-05-23 14:16:54
...

·如果在不能修改Book类定义的情况下是不可能使用Comparable接口的,为此Java提供了另一个比较器java.util.Comparator接口下两个方法:

public interface Comparator<T> {
	public int compare(T o1, T o2);

	public boolean equals(Object obj);
}

示例:

·真正有用的只有compare()方法,需要单独建一个类实现Comparator接口。

·使用Comparator接口后用的是Arrays类另一个被重载的sort方法:

Java 挽救的比较器(Comparator)

import java.util.Arrays;
import java.util.Comparator;

class Book {
	private String title;
	private double price;

	public Book(String title, double price) {
		this.title = title;
		this.price = price;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	@Override
	public String toString() {
		return "书名:《" + this.title + "》价格:" + this.price + "元。";
	}
}

class BookComparator implements Comparator<Book> {
	@Override
	public int compare(Book o1, Book o2) {
		if (o1.getPrice() > o2.getPrice()) {
			return 1;
		} else if (o1.getPrice() < o2.getPrice()) {
			return -1;
		} else {
			return 0;
		}
	}

}

public class Demo {
	public static void main(String[] args) {
		Book books[] = new Book[] {
				new Book("MySQL", 55.8),
				new Book("Androis", 50.7),
				new Book("Oracle", 55.7),
				new Book("Java", 48.8), 
				new Book("JSP", 43.7)

		};
		Arrays.sort(books, new BookComparator());
		for (Book book : books) {
			System.out.println(book);
		}
	}
}
Java 挽救的比较器(Comparator)


相关标签: java comparator