You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
43 lines
1.1 KiB
43 lines
1.1 KiB
package com.example.datacollect.repository;
|
|
|
|
import com.example.datacollect.model.Article;
|
|
import java.util.ArrayList;
|
|
import java.util.Collections;
|
|
import java.util.List;
|
|
|
|
public class ArticleRepository {
|
|
private final List<Article> articles = new ArrayList<>();
|
|
|
|
public void add(Article article) {
|
|
if (article == null) {
|
|
throw new IllegalArgumentException("Article cannot be null");
|
|
}
|
|
articles.add(article);
|
|
}
|
|
|
|
public void addAll(List<Article> newArticles) {
|
|
// 防御 null:传入的集合不能为 null
|
|
if (newArticles == null) {
|
|
return;
|
|
}
|
|
// 遍历添加,同时防御集合中的 null 元素
|
|
for (Article article : newArticles) {
|
|
if (article != null) {
|
|
articles.add(article);
|
|
}
|
|
}
|
|
}
|
|
|
|
public List<Article> getAll() {
|
|
// 返回不可修改集合(作业要求:防止外部篡改)
|
|
return Collections.unmodifiableList(articles);
|
|
}
|
|
|
|
public int size() {
|
|
return articles.size();
|
|
}
|
|
|
|
public void clear() {
|
|
articles.clear();
|
|
}
|
|
}
|
|
|