代码:
import java.util.ArrayList;
import java.util.Arrays;
public class practice{
public static void main(String[] args) {
ArrayList<Phone> 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<Phone> phoneList = func(list);
for(int i=0;i<phoneList.size();i++){
Phone phone = phoneList.get(i);
System.out.println(phone.getBrand()+","+phone.getPrice());
}
}
public static ArrayList<Phone> func(ArrayList<Phone>list){
//定义一个集合
ArrayList<Phone> resultlist = new ArrayList<>();
for(int i=0;i<list.size();i++){
Phone p = list.get(i);
double price = p.getPrice();
if(list.get(i).getPrice()<3000){
resultlist.add(p);
}
}
return resultlist;
}
}
public class Phone{
private String brand;
private double price;
public Phone() {
}
public Phone(String brand, double price) {
this.brand = brand;
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
结果:
如果在方法中打印元素的话,虽然也可以实现输出符合条件的元素,但是后续如果要使用就不方便。