[英]Find class object on HashSet
Dogs a = new Dogs("Samy", 5, "Terrier");
Cats b = new Cats("Lucas", 1, "Siames");
Set<Protectora> animales = new HashSet<Protectora>();
animales.add(a);
animales.add(b);
我怎么才找到Cats
?
使用instanceof
關鍵字:
Set<Cat> cats = new HashSet<Cat>();
for (Object o : animales) {
if (o instanceof Cat) cats.add(o);
}
希望你的Cat
和Dog
類擴展一些父類,比如Animal
,在這種情況下你會寫:
Set<Animal> animals = new HashSet<Animal>();
animals.add(dog);
animals.add(cat);
//add more animals here
Set<Cat> cats = new HashSet<Cat>();
for (Animal a : animals) {
if (a instanceof Cat) cats.add((Cat) o);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.