티스토리 뷰

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayVsArrayList {
	public static void main(String[] args) {
		
		// Arrays 특징
		// - 제네릭 불가능(불안전 유형)
		// - 생성시 크기가 고정되며 확장하거나 축소 할 수 없다.
		// - 초기화 시 메모리에 할당되며, 고정크기여서 속도가 빠르다.
		
		// String[] friendsArray  = new String[4];
		String[] friendsArray = {"John", "Chris", "Eric", "Luke"};
		
		// ArrayList 특징
		// - 제네릭 가능(안전한 유형)
		// - 요소의 수에 따라 자동으로 확장 및 축소 한다.
		// - 확장 및 축소시 메모리를 재할당하며, 동적 특성 때문에 상대적으로 느리다.
		
		// ArrayList<String> friendsArrayList = new ArrayList<>();
		ArrayList<String> friendsArrayList = new ArrayList<>(Arrays.asList("John", "Chris", "Eric", "Luke"));
		
		// Get element
		System.out.println(friendsArray[1]);
		System.out.println(friendsArrayList.get(1));
		
		// Get size
		System.out.println(friendsArray.length);
		System.out.println(friendsArrayList.size());
		
		// Add an element
		// Array는 요소의 크기가 고정되어 있기 때문에 요소를 추가할 수 없다.
		friendsArrayList.add("Mitch");
		System.out.println(friendsArrayList.get(4));
		
		// Set an element
		friendsArray[0] = "Carl";
		System.out.println(friendsArray[0]);
		friendsArrayList.set(0, "Carl");
		System.out.println(friendsArrayList.get(0));
		
		// Remove and element
		// Array는 고정된 크기 때문에 요소를 제거할 수 없다.
		friendsArrayList.remove("Chris");
		System.out.println(friendsArrayList.get(1));
		
		// Print 
		// - Array는 불편한 방법으로 print되며, ArrayList는 편한 방법으로 print된다.
		System.out.println(friendsArray);
		System.out.println(friendsArrayList);
	}
}

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함