首页 > 其他 > 详细

job03

时间:2020-08-08 19:38:46      阅读:84      评论:0      收藏:0      [点我收藏+]
import java.util.TreeSet;

/*键盘输入3本书按照价格从低到高排序后输出,如果价格相同则按照书名的自然顺序排序;
**要求:**
1:书以对象形式存在,包含书名和价格(int类型)两个属性;
2:要求即使直接打印书对象的时候,也能看到书的名称和价格,而不是书对象的地址值;
3:分别使用自然排序和比较器排序实现效果;*/
public class job03 {
public static void main(String[] args) {
net();
net2();

}

public static void net2() {
TreeSet<Book1> treeSet1=new TreeSet<Book1>(
(Book1 a,Book1 b)->{
int result=a.getPrice()-b.getPrice();
result=(result==0)?a.getName().compareTo(b.getName()):result;
return result;
});
Book1 bo1=new Book1("水浒传",98);
Book1 bo2=new Book1("西游记",100);
Book1 bo3=new Book1("红楼梦",98);
treeSet1.add(bo1);
treeSet1.add(bo2);
treeSet1.add(bo3);
System.out.println(treeSet1);
}

public static void net() {
TreeSet<Book> treeSet=new TreeSet<>();
Book b1=new Book("水浒传",98);
Book b2=new Book("西游记",100);
Book b3=new Book("红楼梦",98);
treeSet.add(b1);
treeSet.add(b2);
treeSet.add(b3);
System.out.println(treeSet);
}
}




public class Book implements Comparable<Book> {
private String name;
private int price;

public Book() {
}

public Book(String name, int price) {
this.name = name;
this.price = price;
}

public String getName() {
return name;
}

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

public int getPrice() {
return price;
}

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

@Override
public String toString() {
return "Book{" +
"name=‘" + name + ‘\‘‘ +
", price=" + price +
‘}‘;
}

@Override
public int compareTo(Book o) {
int result=this.price-o.price;
result=(result==0)?this.name.compareTo(o.name):result;
return result;
}
}






public class Book1 {
private String name;
private int price;

public Book1() {
}

public Book1(String name, int price) {
this.name = name;
this.price = price;
}

public String getName() {
return name;
}

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

public int getPrice() {
return price;
}

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

@Override
public String toString() {
return "Book{" +
"name=‘" + name + ‘\‘‘ +
", price=" + price +
‘}‘;
}
}

job03

原文:https://www.cnblogs.com/xiaofeiji/p/13459021.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!