CodeBlanks Logo Icon CodeBlanks

Data model

Set up the data model and collections.

The Catalog class and ArrayList

To manage multiple books you write a Catalog class. It contains an ArrayList<Book> and an addBook method that adds a new book.

import java.util.ArrayList;
class Catalog {
  ArrayList<Book> books = new ArrayList<>();
  void addBook(String title) {
    books.add(new Book(title));
  }
}

addBook takes a title, creates a new Book and adds it to the list. ArrayList is a dynamic array; you do not manage capacity. To print the list, System.out.println(cat.books) is enough; toString shows each book.

Print the list

System.out.println(cat.books) prints the whole list. The ArrayList's toString separates items with commas and wraps them in square brackets. Each Book's own toString is called.

cat.addBook("Suç ve Ceza");
cat.addBook("Sefiller");
System.out.println(cat.books);
// [[müsait] Suç ve Ceza, [müsait] Sefiller]

This lets you see the list contents without writing a separate loop. Notice how the toString design in the Book class pays off here; a good toString makes debugging easier.

Practice Add two books and print them

Add a void addBook(String title) method to the Catalog class: create a new Book and add it to the books list. In main call cat.addBook("Suç ve Ceza") and cat.addBook("Sefiller"), then print cat.books.

Starter code

Main.java
import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    Catalog cat = new Catalog();
    // Add two books and print the list
  }
}

class Book {
  String title;
  boolean available;
  Book(String title) {
    this.title = title;
    this.available = true;
  }
  public String toString() {
    return (available ? "[müsait] " : "[ödünç] ") + title;
  }
}

class Catalog {
  ArrayList<Book> books = new ArrayList<>();
  // Write the addBook method: create a new Book and add to books
}

Sample solution

Main.java
// inside Catalog:
void addBook(String title) {
  books.add(new Book(title));
}
// inside main:
cat.addBook("Suç ve Ceza");
cat.addBook("Sefiller");
System.out.println(cat.books);

Expected output

[[müsait] Suç ve Ceza, [müsait] Sefiller]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each concept to its purpose

Term Meaning
ArrayList<Book> Book list
addBook(String) Add book
new Book(title) Create object
books.add(...) Put in list

2 What does addBook("Suç ve Ceza") do?

  • Removes a book from the list
  • Borrows the book
  • Creates a new Book and adds it to the list Correct answer
  • Prints the list

Explanation: addBook creates a new Book object and adds it to the ArrayList.

3 Call addBook

Question
Catalog cat = new Catalog();
cat.____("Sefiller");
Answer
Catalog cat = new Catalog();
cat.addBook("Sefiller");

Explanation: addBook takes a title and adds a new book to the list.

All lessons in Beginner