public static void main(String[] args) {
ArrayList<Animal> list = new ArrayList<>();
list.add(new Animal("喵喵",2,"波斯喵"));
list.add(new Animal("汪汪",4,"泰迪"));
list.add(new Animal("咕咕",5,"鸽子"));
//调用方法,遍历集合
ArrayList<Animal> c = compare (list);
Iterator<Animal> it = c.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
//定义方法找到一组小动物中,年龄大于等于3岁的。将这些小动物返回成一个集合。
public static ArrayList<Animal> compare(ArrayList<Animal> list) {
ArrayList<Animal> al = new ArrayList<>();
for (Animal a : list) {
if (a.getAge() >= 3) {
al.add(a);
}
}
return al;
}
}
//定义动物类
class Animal {
private String name;
private int age;
private String kind;
public Animal() {
super();
}
public Animal(String name, int age, String kind) {
super();
this.name = name;
this.age = age;
this.kind = kind;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
@Override
public String toString() {
return "Animal [name=" + name + ", age=" + age + ", kind=" + kind + "]";
} |