views:

204

answers:

5

I have a book class, then a novel- and a science book class that extend the book class.

I made an ArrayList using the book class, then inserted the novels and the science books into that. Now I'm trying to iterate through the ArrayList to count how many novels are there. How can I tell?

Would love to see some examples of this! I've been at it for a while.

+5  A: 

Use instanceof.

e.g.

    int numberOfNovels = 0;
    for(int i = 0; i < arrayOfBooks.length; i++){
       if(arrayOfBooks[i] instanceof Novel){
          numberOfNovels++;
       }
    }

Or, using a foreach:

 int numberOfNovels = 0;
 for(Book book: arrayOfBooks){
    if(books instanceof Novel){
       numberOfNovels++;
    }
 }
froadie
It is complete answer.
SjB
Awesome, great examples.
cc0
+4  A: 

You can use instanceof to check the real type of an object:

List<Book> books = new ArrayList<Book>();
books.add(aNovel);
books.add(aScienceBook);

int novelCount = 0;

for (Book book : books) {
    if (book instanceof Novel)
        novelCount++;
}
Péter Török
Excellent, thank you!
cc0
+2  A: 

You could do something along these lines:

public int getNovelCount(List<Book> bookList) {
    int novelCount = 0;
    for (Book book : bookList) {
        if (book instanceof Novel) {
            novelCount++;
        }
    }
    return novelCount;
}

The if statement will only be true for objects that are Novel objects, i.e. science book objects will return false at the if statement and therefore not be counted.

Peter Nix
+4  A: 

Although Froadie is correct in saying that instanceof will allow you to check the specific type of each element, this is generally a sign that there is something wrong with your design.

It might be worth considering why you have to know the number of novels. Do you want to call a method on a novel that doesn't exist on book? Is the collection you're using for all books maybe the wrong way to group the books? If you want to provide methods that do counting of some kind, is it worth considering a way to abstract how the books are counted?

If you find that this case does not raise design concerns, instanceof is your answer.

Grundlefleck
Great feedback, I will certainly take this into consideration for when I do something bigger.
cc0
A: 

Could either use instanceof or book.getClass.equals(Novel.class) . Either way loop though the ArrayList in a for loop:

int count = 0;
for(Book book: books){
   if(book.getClass.equals(Novel.class)) count++;
}
return count;
Adam
Ahhh, so that's how that works! Thank you! I tried to implement that.
cc0
if at a later time you were to use JPA, this wouldn't work.
TJ
instanceof is better than this approach. I was just suggesting another way.
Adam