遍历集合实现冒泡排序
import java.util.ArrayList;
import java.util.List;
/**
* ArrayList冒泡排序
*
* @author ttc
*
*/
public class ListExercise02 {
@SuppressWarnings("all")
public static void main(String[] args) {
List list = new ArrayList();
list.add(new Book("张三", "人间失格", 108));
list.add(new Book("李四", "莎士比亚", 20));
list.add(new Book("apple", "理想国", 210));
list.add(new Book("abc", "西游记", 120));
for (Object o : list) {
System.out.println(o);
}
for (int i = 0; i < list.size() - 1; i++) {
for (int j = 0; j < list.size() - i - 1; j++) {
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);
}
}
}
System.out.println("====");
for (Object o : list) {
System.out.println(o);
}
}
}
class Book {
private String name;
private String writer;
private double price;
public Book(String name, String writer, double price) {
this.name = name;
this.writer = writer;
this.price = price;
}
public Book() {
}
public Book(String name, String writer) {
this.writer = writer;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "书名:" + name + "\t\t" + "作者:" + writer + "\t\t " + "价格:" + "\t\t" + price;
}
}
要求按照价格从小到大进行输出:
**
for (int i = 0; i < list.size() - 1; i++) {
for (int j = 0; j < list.size() - i - 1; j++) {
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);
}
通过(Book)强制类型转换将list.get()的结果转成Book类型,来调用Book类型的getPrice()方法,通过比较getPrice()返回值的大小,进行冒泡排序,用list.set(int index,Object element)方法实现list集合元素交换顺序
输出结果