添加手机对象并返回要求的数据
需求:
- 定义Javabean类:Phone
- Phone属性:品牌,价格
- main方法中定义一个集合,存入三个手机对象。分别为:小米,1000。苹果,8000。oppo , 2999。
- 定义一个方法,将价格低于3000的收据信息返回。
测试类
import java.util.ArrayList;
public class FTest {
public static void main(String[] args) {
/*
* 添加手机对象并返回要求的数据
* 需求:
* 1.定义Javabean类:Phone
* 2.Phone属性:品牌,价格
* 3.main方法中定义一个集合,存入三个手机对象。分别为:小米,1000。苹果,8000。oppo , 2999。
* 4.定义一个方法,将价格低于3000的收据信息返回。
* */
//1.创建对象集合
ArrayList<Phone> list = new ArrayList<>();
//2.创建并添加三个手机对象
Phone p1 = new Phone("小米",1000);
Phone p2 = new Phone("苹果",8000);
Phone p3 = new Phone("锤子",2999);
//3.添加数据
list.add(p1);
list.add(p2);
list.add(p3);
//4.调用方法
ArrayList<Phone> phoneInfoList = getPhoneInfo(list);
//5.遍历集合
for (int i = 0; i < phoneInfoList.size(); i++) {
System.out.println(list.get(i).getBrand() + list.get(i).getPrice());
}
}
//技巧:
//如果需要返回多个数据,可以把这些数据先放到一个容器当中,再把容器返回
//集合 数组
public static ArrayList<Phone> getPhoneInfo(ArrayList<Phone> list){
//定义一个集合用于存储价格低于3000的手机对象
ArrayList<Phone> resultList = new ArrayList<>();
//遍历集合
for (int i = 0; i < list.size(); i++) {
//如果当前手机的价格低于3000,那么就把手机对象添加到resultList当中
if (list.get(i).getPrice() < 3000){
resultList.add(list.get(i));
}
}
//返回resultList
return resultList;
}
}
JavaBean类
public class Phone{
private String brand;
private int price;
public Phone() {
}
public Phone(String brand, int price) {
this.brand = brand;
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}