TreeSet implement java generic book price ascending

import java.util.*;

public class Book {
	private String name;
	private String author;
	private String publish;
	private double price;

	public Book() {

	}

	public Book(String name, String author, String publish, double price) {
		super();
		this.name = name;
		this.author = author;
		this.publish = publish;
		this.price = price;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getPublish() {
		return publish;
	}

	public void setPublish(String publish) {
		this.publish = publish;
	}

	public double getPrice() {
		return price;
	}

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

	public int hashCode() {
		return (int) (Math.random() * 100 + 10);
	}
	@Override
	public String toString() {
		return "Book [name= " + name + ", author= " + author + ", publish= " + publish + ", price= " + price + "]";
	}

}

import java.util.Comparator;
import java.util.TreeSet;
	public static void treeSetdemo() {
		TreeSet<Book> ts = new TreeSet<Book>(new BookPrice());
		Book b1 = new Book("java", "李三", "清华", 34);
		Book b2 = new Book("数据结构", "张四", "机械", 43);
		Book b3 = new Book("c++", "吴天", "人邮", 23);
		Book b4 = new Book("数据库", "周一", "高等", 74);
		ts.add(b1);
		ts.add(b2);
		ts.add(b3);
		ts.add(b4);
		for (Book b : ts) {
			System.out.println(b);
		}
	}

	public static void main(String[] args) {
		treeSetdemo();
	}

}
class BookPrice implements Comparator<Book> {
	public int compare(Book o1, Book o2) {
		return (int) (o1.getPrice() - o2.getPrice());
	}
}

Run shot:

Here Insert Picture Description

Published 77 original articles · won praise 19 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_43488547/article/details/103238858