简体   繁体   English

仅从ArrayList获取子类项目

[英]Getting child class items only from an ArrayList

I have an ArrayList<Item> items and two classes which inherit Item , which are Book and DVD . 我有一个ArrayList<Item> items和两个继承Item类,分别是BookDVD I add some books and some dvds in the item list 我在项目列表中添加了一些书和一些DVD

items.add(new Book());
items.add(new DVD());

Now I want to do a 现在我想做一个

public void printAllBooks()
{
}

How can I just pick the Item which is of child class Book to print only? 我如何才能挑选Item是子类的Book只打印?

If you are forced to use a combined list you can use instanceof to check if it's a book.. 如果您被迫使用合并列表,则可以使用instanceof检查它是否是一本书。

public void printAllBooks()
{
    for(Item i : items){
        if(i instanceof Book){
            System.out.println(i);
        }
    }
}

But a better design might be to have separate lists of books and dvds 但是更好的设计可能是将书籍和DVD分开列出

for (Item item : items) {
    if (item instanceof Book) {
        System.out.println(item);
    }
}

One quick solution is to use instanceof : 一种快速的解决方案是使用instanceof

for(Item item : items) {
   if(item instanceof Book) {
      // print it
   }
}

A more generic solution is to make the method generic, giving it a type parameter and checking if the item type is that of the specified class (or a subclass of it): 更通用的解决方案是使方法通用,为其提供类型参数,并检查项目类型是否为指定类(或其子类)的类型:

public <T extends Item> void printItems(List<Item> items, Class<T> clazz) {
    for(Item item : items) {
        // Check if item is of the same type or a subtype of the specified class.
        if(clazz.isAssignableFrom(item.getClass())) {
            // print it
        }
    }
}

Then to print Book elements: 然后打印Book元素:

printItems(itemsList, Book.class);

and similarly for DVD elements: 同样适用于DVD元素:

printItems(itemsList, DVD.class);

Here is the solution 这是解决方案

public void printAllBooks(){
  for(Object item: Items)
     if(item instanceOf Book)
        //do what ever you want
}

You can do: 你可以做:

for(Item item : items) {
   if(item instanceof Book) {
      // do something with Book Item
   }
}

If you're using Guava, you could use the following: 如果您使用的是番石榴,则可以使用以下命令:

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Iterables.html#filter%28java.lang.Iterable,%20java.lang.Class%29 http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Iterables.html#filter%28java.lang.Iterable,%20java.lang.Class%29

For your example, something like this would work: 对于您的示例,这样的事情会起作用:

Iterable<DVD> dvds = Iterables.filter(items,DVD.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM