Java利用多态知识解决从Animal数组中挑选出所有Dog对象,并把这些对象放在数组中返回

@Java

大家好,我是Ziph!

题目:从Animal数组中挑选出所有Dog对象,并把这些对象放在数组中返回

import java.util.Arrays;

/** 
* @author Ziph
* @date 2020年2月20日
* @Email [email protected]
*/
public class TestAnimal {
	public static void main(String[] args) {
		Animal[] as = new Animal[] {
			new Dog("Pluto"),
			new Cat("Tom"),
			new Dog("Snoopy"),
			new Cat("Garfield")
		};
		
		Dog[] dogs = getAllDog(as);
		for (int i = 0; i < dogs.length; i++) {
				System.out.print(dogs[i].getName() + "\t");
		}
	}
	
	public static Dog[] getAllDog(Animal[] as) {
		Dog[] dog = new Dog[0];
		int sign = 0;
		for (int i = 0; i < as.length; i++) {
			if (as[i] instanceof Dog) {
				dog = Arrays.copyOf(dog, dog.length + 1);
				dog[sign] = (Dog)as[i];
				sign++;
			}
		}
		return dog;
	}
}

class Animal {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Animal(String name) {
		this.name = name;
	}
}

class Dog extends Animal {
	public Dog(String name) {
		super(name);
	}
}

class Cat extends Animal {
	public Cat(String name) {
		super(name);
	}
}

第二种getAllDog方法

public static Dog[] getAllDog(Animal[] animals) {
		//0.定义计数器
		int count = 0;
		
		//1.先数一遍,数组中有几只狗,然后再创建数组
		for(int i = 0 ; i < animals.length ; i++) {
			//1.1对数组中每个元素的类型,进行判断
			if(animals[i] instanceof Dog) {
				//1.2每发现一个Dog对象,计数器自增
				count++;
			}
		}
		
		//2.根据记数结果,创建长度合适的Dog数组
		Dog[] dogs = new Dog[count]; // 0 1 2
		
		//3.定于Dog的有效元素个数
		int size = 0;
		
		//4.将animals中的所有Dog对象,保存在Dog数组中
		for(int i = 0 ; i < animals.length ; i++) { 
			//4.1判断是否为Dog类型
			if(animals[i] instanceof Dog) {
				//4.2将Animal数组元素,进行强转后,保存在Dog数组中
				dogs[size] = (Dog)animals[i];// Animal a0 = new Dog();
				//4.3Dog数组的有效元素的计数器自增
				size++;
			}
		}

		//5.将保存了所有Dog对象的数组,返回给方法调用处
		return dogs;
	}

执行结果:

)

发布了49 篇原创文章 · 获赞 94 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44170221/article/details/104418287