배열은 객체를 저장하는 상자다. 저장되어지는 객체는 동일한 타입을 가지고 있어야 하고, 배열의 크기는 생성 전에 정해지고, 그 크기는 변하지 않는다. 각 객체는 배열의 요소가 되고, 0부터 시작하는 index 번호를 갖게 된다.
배열 선언하기
배열을 선언하는 것은 단순히 컴파일러에게 어떤 타입의 객체들을 이 변수에 저장할 것이라고 알려주는 것이다. 실제로 객체를 생성하려면 초기화를 해주어야 한다.
public class Practice {
public static void main(String[] args) {
int[] arr; // arr이라는 배열에 int 타입의 객체들을 담을 것이다.
//이 상태로 실행하면 java: variable arr might not have been initialized 에러 발생
arr = new int[3]; // arr의 크기를 3으로 초기화했다.
System.out.println(arr); // [I@776ec8df
// [ 는 배열이라는 의미고, I는 int type이라는 의미
// int[] arr = {1,2,3}; 선언과 동시에 초기화 할 수도 있음.
}
}
배열을 다루는 데 도움을 주는 Arrays 클래스
import java.util.Arrays;
public class Practice {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(arr)); //[1, 2, 3, 4, 5]
int[] b = Arrays.copyOf(arr, 8); // arr을 복사하는데 새로운 배열의 길이가 만약 2라면 index번호 1번까지,
// 만약 기존의 배열보다 크기가 크면 int타입 배열을 기본값인 0을 채워넣는다.
System.out.println(Arrays.toString(b)); // [1, 2, 3, 4, 5, 0, 0, 0]
int[] c =Arrays.copyOfRange(arr, 1, 3); // arr 배열의 index 1 ~ index 2까지 복사
System.out.println(Arrays.toString(c)); // [2. 3]
}
}
배열을 단점을 보완한 ArrayList
-> 크기가 고정되어 있는 기존의 배열과 달리 크기가 가변적이다.
ArrayList는 List 인터페이스를 구현한 클래스다.
List를 구현한 클래스에는 ArrayList뿐만 아니라, LinekdList, Stack, 그리고 Vector 등이 있다.
import java.util.*;
public class Practice {
public static void main(String[] args) {
List<String> a = new ArrayList<>();
a = new LinkedList<>();
a= new Vector<>();
// 리스트 type 참조변수로 ArrayList 객체를 만들 땐 리스트를 구현한 다른 클래스들로 자유롭게 형변환 가능
ArrayList<String> b = new ArrayList<>();
b = new LinkedList<>(); // 형변환 안됨
}
}
List<String> a = new ArrayList<>();
a = new LinkedList<>();
a.add("Ho");
a.add("H2");
a.add("H33");
a.add("H5");
a.add("H6");
a.add("H9");
System.out.println(a.get(2)); // H33
a.set(2, "H32"); // index 2번을 H32로 변경
System.out.println(a.get(2));
a.remove(0); // index 0번인 Ho 삭제
System.out.println(a.size()); // 5
a.clear();
System.out.println(a.size()); // 0
'자료구조와 알고리즘' 카테고리의 다른 글
힙 (0) | 2022.06.30 |
---|---|
트리 (0) | 2022.06.29 |
hash table (0) | 2022.06.28 |
Stack (0) | 2022.06.16 |
Queue (0) | 2022.06.16 |