List小练习,实现添加图书,并且有序遍历

List小练习,实现添加图书,并且有序遍历_第1张图片

 @SuppressWarnings({"all"})
    public static void main(String[] args) {
        List list = new LinkedList();
//        List list = new Vector();
//        List list = new ArrayList();
        list.add(new Book1("红楼小梦",35.5,"曹雪芹"));
        list.add(new Book1("霸王别姬",98.5,"张艺谋"));
        list.add(new Book1("一代妖姬",30.5,"未知"));
        list.add(new Book1("前任三传",32.5,"郑恺"));
        for (Object o :list) {
            System.out.println(o);
        }
        Bubble(list);
        System.out.println("=========排序后:========");
        for (Object o :list) {
            System.out.println(o);
        }
    }

    //冒泡排序
    public static void Bubble(List list){
        for (int i = 0; i < list.size()-1; i++){
            for (int j = 0; j < list.size()-i-1; j++) {
                    Book1 book1 = (Book1) list.get(j);
                    Book1 book2 = (Book1) list.get(j+1);
            if(book1.getPrice()> book2.getPrice()){
                list.set(j,book2);
                list.set(j+1,book1);
            }
            }
        }
    }
}
class Book1{
    private String name;
    private double price;
    private String author;

    @Override
    public String toString() {
        return "名称:" +
                name +
                "\t\t价格:" + price +
                "\t\t作者:" + 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;
    }

    public Book1(String name, double price, String author) {
        this.name = name;
        this.price = price;
        this.author = author;
    }

List小练习,实现添加图书,并且有序遍历_第2张图片

传送门:为什么这里不需要中间变量就可以直接使用冒泡排序? 

为什么不懂wb​​​​​​​list.set交换数据需要(or不需要)添加其他中间变量,两个例子告诉你-CSDN博客 

你可能感兴趣的:(韩顺平java习题,list,java,数据结构)