List集合练习题 完成getAllDog 方法,从一个Animal集合中挑选出所有的Dog对象,并把这些对象 放在一个Dog 集合中返回。

package cn.sc.test;

import java.util.ArrayList;
import java.util.List;

public class TestAnimal {
public static void main(String[] args) {
List as = new ArrayList();
as.add( new Dog() );
as.add( new Cat() );
as.add( new Dog() );
as.add( new Cat() );
List dogs = getAllDog(as);
//使用2种方式遍历dogs集合,并调用每一个Dog对象的paly方法
for (int i =0;i<dogs.size();i++){
dogs.get( i ).play();
}
for (Dog o:dogs){
o.play();
}
}
public static List getAllDog(List animals){
//完成getAllDog 方法,从一个Animal集合中挑选出所有的Dog对象,并把这些对象放在一个Dog 集合中返回。
List dog = new ArrayList( );
int index =0;
for (int i =0;i<animals.size();i++){
if(animals.get( i ) instanceof Dog){
dog.add( index,new Dog() );
index++;
}
}
return dog;
}
}
class Animal{}
class Dog extends Animal{
public void play(){
System.out.println(“Dog play with you”);
}
}
class Cat extends Animal{}

猜你喜欢

转载自blog.csdn.net/qq_43302785/article/details/83352440