animal类:
public class Animal {
int nNage;
String strName;
public Animal(int nNage, String strName) {
this.nNage = nNage;
this.strName = strName;
}
}
dog类:
public class Dog extends Animal{
public Dog(int nNage, String strName) {
super(nNage, strName);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
else if (obj==null)
return false;
if (!(obj instanceof Dog))
return false;
Dog dog = (Dog) obj;
dog.strName.equals(this.strName);
if ((dog.strName.equals(this.strName))&&
this.nNage == dog.nNage){
return true;
}
return false;
}
@Override
public String toString() {
return "Dog{" +
"nNage=" + nNage +
", strName='" + strName + '\'' +
'}';
}
}
zoo类:
import java.util.ArrayList;
import java.util.List;
public class zoo {
//创建成员变量 保存数据
private List<Animal> animals = new ArrayList<>();
//添加
public void add(Animal animal){
animals.add(animal);
}
//删除
public void remove(Animal animal){
animals.remove(animal);
}
//模糊查询
public List<Animal> search(String key){
List<Animal> retList = new ArrayList<>();
for (Animal animal:animals){
//String中有一个模糊查询的函数
if (animal.strName.contains(key)){
retList.add(animal);
}
}
return retList;
}
public void print() {
for (Animal animal:animals) {
System.out.println(animal.toString());
}
}
}
main类:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
zoo zooobj = new zoo();
zooobj.add(new Dog(1,"小花狗"));
zooobj.add(new Dog(3,"小黑狗"));
zooobj.add(new Dog(5,"小灰狗"));
zooobj.add(new Dog(8,"小灰狗"));
zooobj.add(new Dog(10,"小灰狗"));
zooobj.remove(new Dog(1,"小花狗"));
zooobj.print();
System.out.println("---------------------------");
List<Animal> retList = zooobj.search("灰");
for (Animal animal:retList){
System.out.println(animal.toString());
}
}
}