题目:
代码:
public class ListMethod {
@SuppressWarnings({"all"})
public static void main(String[] args) {
List list = new ArrayList();
list.add(new Book("红楼梦", 100, "曹雪芹"));
list.add(new Book("西游记", 10, "吴承恩"));
list.add(new Book("水浒传", 9, "施耐庵"));
list.add(new Book("三国演义", 80,"罗贯中"));
//排序前
System.out.println("=====排序前====");
Iterator iterator = list.iterator();
while(iterator.hasNext()) {
Object obj = iterator.next();
System.out.println("obj=" + obj);
}
// for (Object o :list) {
// System.out.println(o);
// }
//冒泡排序
sort(list);
System.out.println("====从低到高排序后===");
for (Object o :list) {
System.out.println(o);
}
}
//静态方法
//价格要求是从小到大
public static void sort(List list) {
for (int i =0; i <list.size()-1; i++) {
for(int j = 0; j < list.size()-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);
}
}
}
}
}
class Book {
private String name;
private double price;
private String author;
public Book(String name, double price, String author) {
this.name = name;
this.price = price;
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "名称:" + name + "\t\t" + "价格:" + price + "\t\t" + "作者:" + author;
}
}
输出结果:
=====排序前====
obj=名称:红楼梦 价格:100.0 作者:曹雪芹
obj=名称:西游记 价格:10.0 作者:吴承恩
obj=名称:水浒传 价格:9.0 作者:施耐庵
obj=名称:三国演义 价格:80.0 作者:罗贯中
====从低到高排序后===
名称:水浒传 价格:9.0 作者:施耐庵
名称:西游记 价格:10.0 作者:吴承恩
名称:三国演义 价格:80.0 作者:罗贯中
名称:红楼梦 价格:100.0 作者:曹雪芹