1.代码实现
package list;import java.util.ArrayList;import java.util.Iterator;import java.util.List;public class test2 { public static void main(String[] args) { List list=new ArrayList(); list.add(new Book("三国",67.2)); list.add(new Book("水浒",44.3)); list.add(new Book("红楼梦",27.2)); list.add(new Book("活着",23.4)); System.out.println("排序前为:"); for(Object o:list){ System.out.println(o); } //冒泡排序 bubble(list); System.out.println("排序后为:"); Iterator iterator = list.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } } //冒泡排序 public static void bubble(List list){ for(int i=0;i< list.size()-1;i++){ for(int j=0;jbook2.getPrice()){ //按照升序进行排序 list.set(j,book2); list.set(j+1,book1); } } } }}class Book{ private String name; private double price; public Book(String name, double price) { this.name = name; this.price = price; } public String getName() { return name; } public double getPrice() { return price; } @Override public String toString() { return "Book{" + "name='" + name + ''' + ", price=" + price + '}'; }}
2.测试