java实现的ArrayList对对象的属性进行排序。。。

1.对象转化为向下转型

2.得到属性值

3.比较判断

4.用set方法把对象放进去

5.遍历看效果

import java.util.*;
/**
 * @version 1.0
 * function:
 * @author:阿卜杜赛麦提
 * @date:2023/1/4 19:18
 */
@SuppressWarnings({"all"})
public class ListExercise02 {
    public static void main(String[] args) {
        List list = new ArrayList();
        Random random = new Random();
        for (int i = 1; i <=5; i++) {
            double v = random.nextDouble()*100;
            String v1 = String.format("%.1f", v);
            double v2 = Double.parseDouble(v1);
            list.add(new Book1("java从入门到放弃"+i+"号",v2,"阿卜杜"+i+"号"));
        }

//        System.out.println(list);
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            Object next = iterator.next();
            System.out.println(next);
        }

        System.out.println("==============普通for循环==============");
        for (int i = 0; i <list.size() ; i++) {
            Object o = list.get(i);
            System.out.println( ((Book1)o).getPrice());
        }
        for (int i = 0; i < list.size()-1; i++) {
            for (int j = 0; j < list.size()-1-i; 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);
                    }

            }
        }
        System.out.println("================排序完后==========");
        for (Object o :list) {
            System.out.println(o);
        }
    }
}
class Book1{
    private String name;
    private double price;
    private String author;

    public Book1(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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿卜杜赛麦提爱编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值