java
复制代码
package ArrayListDemo;
import java.util.ArrayList;
public class ArrayListDemo7 {
public static void main(String[] args) {
//1.创建集合对象
ArrayList<Phone> list = new ArrayList<Phone>();
//2.创建手机对象
Phone ph1 = new Phone("小米",1000);
Phone ph2 = new Phone("苹果",8000);
Phone ph3 = new Phone("锤子",2999);
Phone ph4 = new Phone("鸭梨",1999);
//3.添加数据
list.add(ph1);
list.add(ph2);
list.add(ph3);
ArrayList<Phone> phoneInfo = getPhoneInfo(list);
phoneInfo.add(ph4);
for (int i = 0; i < phoneInfo.size(); i++) {
Phone phone = phoneInfo.get(i);
System.out.println(phone.getPinpai()+","+phone.getJiage());
}
}
//技巧:
//如果我们要返回多个数据,可以把这些数据先放到一个容器当中,再把容器返回
//集合,数组
public static ArrayList<Phone> getPhoneInfo(ArrayList<Phone> list){
//定义一个集合,用于存储价格低于三千的对象
ArrayList<Phone> resultList = new ArrayList<Phone>();
for (int i = 0; i < list.size(); i++) {
Phone p = list.get(i);
int jiage = p.getJiage();
//如果当前手机的设备低于3000,那么就把手机对象添加到resultList中
if(jiage < 3000){
resultList.add(p);
}
}
return resultList;
}
}