java 泛型TreeSet实现书本价格升序排列

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());
	}
}

运行截图:

在这里插入图片描述

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值