컬렉션이란(Collections) ?
한글로 말하면 자료구조이다. 더 쉽게 말하면 배열이다. JAVA 데이터를 효과적으로 관리하기 위한 언어이다. 자양한 자료구조형이 제공되는 이유는 데이터의 성질에 따라서 데이터를 관리해야하는 방식이 다르기 때문이다. 중요한것은 자료구조형 안에서는 객체의 레퍼런스만 관리 한다.
List계열 컬렉션 클래스 살펴보기
자료구조중 가장 많이 사용? 하고 쉽게 사용할수 있는 계열이 List계열이다.
List는 배열과 비슷하지만 배열의 단점을 보완하였다, List는 처음 만들때 크기를 고정하지 않아도된다.
ArrayList 사용방법
package sutdy.java.ex19_Collections.arrayList;
import java.util.ArrayList;
public class ArrayListTest {
public static void main(String[] args) {
//arrayList 객체 생성
ArrayList<String> al = new ArrayList<String>();
//리스트에 데이터를 넣을때 사용하는 메서드는 add
al.add("str1"); // index 0번
al.add("str2"); // index 1번
al.add("str3"); // index 2번
al.add("str4"); // index 3번
System.out.println(al.toString());
String index3 = al.get(3); //3번째 index 값을 가지고와서 index3 변수에 저장
System.out.println(index3);
al.set(2, "str22222"); // 2번째 index값을 가지고와서 str22222 로 변경한다.
System.out.println(al.toString());
int size = al.size(); //크기가 얼마인지 알려준다.
System.out.println("size : " +size);
al.remove(2); //index 가 2번째 인것을 삭제한다.
System.out.println(al.toString());
al.clear(); //인덱스값을 모두다 삭제된다.
System.out.println(al);
al = null; // 배열을 비운다.
System.out.println(al);
System.out.println(al.size()); // error NullPointerException 이 뜬다.
}
}
결과값
[str1, str2, str3, str4] str4 [str1, str2, str22222, str4] size : 4 [str1, str2, str4] [] null