package com.collection_.list_;
public class Book {
private String name;
private String auther;
private double price;
public Book(String name, String auther, double price) {
this.name = name;
this.auther = auther;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuther() {
return auther;
}
public void setAuther(String auther) {
this.auther = auther;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "名称:" + name + "\t" + "价格:" + price + "\t" + "作者:" + auther + "\n";
}
}
package com.collection_.list_;
import java.util.ArrayList;
import java.util.List;
public class ListExercise {
@SuppressWarnings("all")
public static void main(String[] args) {
List list = new ArrayList();
//List list = new Vector();
//List list = new LinkedList();
list.add(new Book("红楼梦","曹雪芹",100));
list.add(new Book("西游记","吴承恩",10));
list.add(new Book("水浒传","施耐庵",9));
list.add(new Book("三国","罗贯中",80));
list.add(new Book("西游记","吴承恩",90));
//遍历
for (Object o :list) {
System.out.println(o);
}
//冒泡排序
System.out.println("===排序后结果===");
sort(list);
for (Object o : list) {
System.out.println(o);
}
}
//价格要求从小到大
public static void sort(List list){
int listsize = list.size();
for (int i = 0; i < listsize-1; i++) {
for (int j = 0; j < listsize-1-i; j++) {
//取出对象Book
Book book1 = (Book) list.get(j);
Book book2 = (Book) list.get(j+1);
if (book1.getPrice() > book2.getPrice()){ //交换
list.set(j,book2);
list.set(j+1,book1);
}
}
}
}
}
标签:String,price,练习,list,Book,集合,排序,public,auther
From: https://www.cnblogs.com/Q1u-ovo/p/17287016.html