ᴘᴀɴᴀʏɪᴏᴛɪs
ᴘᴀɴᴀʏɪᴏᴛɪs

Reputation: 7529

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. I add some books and some dvds in the item list

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?

Upvotes: 0

Views: 520

Answers (6)

Navin Viswanath
Navin Viswanath

Reputation: 894

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

For your example, something like this would work:

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

Upvotes: 0

M A
M A

Reputation: 72854

One quick solution is to use 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:

printItems(itemsList, Book.class);

and similarly for DVD elements:

printItems(itemsList, DVD.class);

Upvotes: 1

gashu
gashu

Reputation: 494

You can do:

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

Upvotes: 0

Junaid S.
Junaid S.

Reputation: 2642

Here is the solution

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

Upvotes: 0

David ten Hove
David ten Hove

Reputation: 2826

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

Upvotes: 3

dkatzel
dkatzel

Reputation: 31648

If you are forced to use a combined list you can use instanceof to check if it's a book..

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

Upvotes: 5

Related Questions