遍历集合实现冒泡排序

遍历集合实现冒泡排序

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集合元素交换顺序

输出结果
输出结果

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值