우리가 평소에 배열을 사용할 때 혹시 불편한점 느낀거 있어? 아직 배열도 잘 모르겠는데..
나는 배열을 사용할 때 불편한 점이 배열은 선언할 때 크기를 정해두고 선언을 하니까 나중에 값을 추가로 늘릴수가 없다는게 좀 불편하다고 생각했어. 그래서 이런 불편한 점을 개선해서 나온게 ArrayList야.
static void v1() {
System.out.println("==v1==");
Article[] articles = new Article[100];
int articlesSize = 0;
articles[0] = new Article();
articlesSize++;
articles[1] = new Article();
articlesSize++;
articles[2] = new Article();
articlesSize++;
articles[3] = new Article();
articlesSize++;
articles[4] = new Article();
articlesSize++;
for (int i = 0; i < articlesSize; i++) {
System.out.println(articles[i].id);
}
}
class Article {
static int lastId;
int id;
String regDate;
static {
lastId = 0;
}
Article() {
this(lastId + 1, "2025-12-12 12:12:12"); // 다른 생성자 호출(실행), Constructor Call
lastId++;
}
Article(int id, String regDate) {
this.id = id;
this.regDate = regDate;
}
}
우리가 배열을 사용할 때 articles 배열의 크기는 100 이잖아? 그러면
articles[0]부터 [100]번 까지 new을 이용해 만들고 ++증감 연산자를 통해 공간도 하나씩 늘려주고 이러한 행동을 했는데 ArrayList를 이용하면 우리가 원하는 만큼의 데이터를 저장 할 수 있게 될거야.
static void v4() {
System.out.println("==v4==");
List<Article> articles = new ArrayList<>();
articles.add(new Article()); // index : 0 , id : 1
articles.add(new Article()); // index : 1 , id : 2
articles.add(new Article()); // index : 2 , id : 3
for (int i = 0; i < articles.size(); i++) {
Article article = articles.get(i);
System.out.println(article.id);
}
}
ArratList사용법이야. List는 ArrayList의 상위 클래스라고 보면 돼. 그래서 List
articles = new ArrayList<>(); 이런 형태로 사용 될 수 있고 <>이건 제네릭이라고 불려. 뒤에 부분은 우리가 객체 생성할 때랑 비슷한 모양이지? 그리고 값은 어떤식으로 추가하냐면 변수명.add를 해주면 된다. 이 코드에서는 article.add()하고 new Article()를 해서 Article 클래스에 있는 생성자를 호출해 새로운 Article 객체를 만들어 하나씩 추가 할 수 있어. 그래서 ArrayList를 좀 더 많이 활용해보면 배열을 이용해 객체를 다루는것 보다 좀 더 유용하게 활용될거야.