Java
Blog class
Set up collection management with the Blog class.
The Blog class manages the collection
Once you have a single Post instance, you need to collect them in a list. The Blog class does this: it holds a List<Post> named posts and adds new posts through an addPost method.
The line List<Post> posts = new ArrayList<>(); gives every new Blog instance an empty list. ArrayList behaves like a dynamic array; you append with add.
The addPost method
The addPost method does one thing in a single line: posts.add(post);. To call it you write blog.addPost(new Post(...)); the Post instance is ready in one line.
After adding, blog.posts.size() tells you how many posts the blog has. This count confirms the add worked.
Exercise Write the Blog class and addPost method
The Post and Comment classes from above are ready. Now define class Blog with a List<Post> posts field initialized to an empty ArrayList, and a void addPost(Post post) method that calls posts.add(post);. In main, create a Blog blog = new Blog();, add two posts, and print the count with System.out.println(blog.posts.size());.
Show example solution
class Post {
String title;
String author;
Post(String title, String author) {
this.title = title;
this.author = author;
}
}
class Comment {
String author;
String text;
Comment(String author, String text) {
this.author = author;
this.text = text;
}
}
class Blog {
List<Post> posts = new ArrayList<>();
void addPost(Post post) { posts.add(post); }
}
public class Main {
public static void main(String[] args) {
Blog blog = new Blog();
blog.addPost(new Post("First", "Ayşe"));
blog.addPost(new Post("Second", "Mehmet"));
System.out.println(blog.posts.size());
}
}
Test yourself
-
Complete the list declaration
List<Post> posts = new ____<>();
Show answer
List<Post> posts = new ArrayList<>();
-
What does blog.posts.size() return?
- The title of the first post
- The memory address of the list
- The authors of the posts
- The number of posts in the list
Show answer
The number of posts in the list — size() returns the number of elements in the list.
-
Match the Blog class concepts
- List<Post>
- Post collection type
- ArrayList<>
- Concrete list implementation
- addPost
- Adds a post to the list
- size()
- Number of elements in the list
Next lesson: Adding comments