Java零基础学习20:集合的练习

编写博客目的:本系列博客均根据B站黑马程序员系列视频学习和编写目的在于记录自己的学习点滴,方便后续回忆和查找相关知识点,不足之处恳请各位有缘的朋友指正。

一、查找id对应的集合索引

package www.itheima;

import java.util.ArrayList;

public class ArrayListDemo7 {
    public static void main(String[] args) {
        ArrayList list = new ArrayList<>();

        User u1 = new User("001", "zhangsan", "123456");
        User u2 = new User("002", "wangwu", "123456");
        User u3 = new User("003", "lisi", "123456");

        list.add(u1);
        list.add(u2);
        list.add(u3);

        System.out.println(getIndex(list,"002"));
    }

    public static int getIndex(ArrayList list, String id) {
        for (int i = 0; i < list.size(); i++) {
            User u = list.get(i);
            String uid = u.getId();
            if (uid.equals(id)) {
                return i;
            }
        }
        return -1;
    }
}

二、返回手机价格低于三千的手机

package www.itheima;

import java.util.ArrayList;

public class ArrayListDemo8 {
    public static void main(String[] args) {
        ArrayList list = new ArrayList<>();

        Phone p1 = new Phone("小米", 1000);
        Phone p2 = new Phone("苹果", 8000);
        Phone p3 = new Phone("锤子", 2999);

        list.add(p1);
        list.add(p2);
        list.add(p3);

        ArrayList phoneInfoList = getPhoneInfo(list);
        for (int i = 0; i < phoneInfoList.size(); i++) {
            Phone phone = phoneInfoList.get(i);
            System.out.println(phone.getBrand() + "," + phone.getPrice());
        }
    }

    // 定义一个方法,返回手机价格低于3000的手机
    public static ArrayList getPhoneInfo(ArrayList list) {
        ArrayList resultList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Phone p = list.get(i);
            int price = p.getPrice();
            if (price < 3000) {
                resultList.add(p);
            }
        }
        return resultList;
    }
}

你可能感兴趣的:(学习)