Java의 데이터 타입과 예외
Jim White
Java Developer
List 인터페이스, Collection의 하위 인터페이스List의 여러 구현ArrayList: 크기 조절 가능, 인덱스(배열처럼) 기반, 순서 있는 객체 리스트
LinkedList: 다음/이전 객체로 연결된 리스트
new로 인스턴스 생성, 제네릭으로 내용 타입 지정.add(object)로 끝에 추가.get(index)로 접근ArrayList는 0부터 시작.set(index, object)로 교체.remove(index)로 제거.clear()로 모두 비우기.size()로 개수 확인import java.util.ArrayList; ... ArrayList<String> animals = new ArrayList<String>();animals.add("horse"); animals.add("cow"); animals.add("horse"); // 중복 허용String c = animals.get(1); // c="cow" animals.set(1, "chicken");// 첫 번째 horse 제거 animals.remove(0); // 모든 객체 제거 animals.clear();animals.size();
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(new Integer(5));
list.add(6); // 6이 자동으로 Integer로 감싸진 뒤 추가
Object 사용ArrayList<Object> list = new ArrayList<Object>(); // 어떤 객체든 허용
list.add(new Integer(5)); // Integer 추가
list.add(6); // 오토박싱으로 Integer 추가
list.add("Hello"); // String 추가
List의 객체를 순회하려면 for-each 구문 사용ArrayList<String> animals = new ArrayList<String>();
animals.add("horse");
animals.add("cow");
animals.add("chicken");
for (String animal : animals) { // ArrayList 전체 순회
System.out.println(animal);
}
horse
cow
chicken
List 인스턴스(예: ArrayList)의 내용은 println으로 출력 가능ArrayList<String> animals = new ArrayList<String>();
animals.add("horse");
animals.add("cow");
animals.add("chicken");
System.out.println(animals); // ArrayList의 모든 요소 출력
ArrayList<Object> list = new ArrayList<Object>();
list.add(5);
list.add("Hello");
System.out.println(list); // ArrayList의 모든 요소 출력
[horse, cow, chicken]
[5, Hello]
LinkedList는 ArrayList처럼 생성합니다LinkedList는 ArrayList와 같은 메서드를 가집니다import java.util.LinkedList;
...
LinkedList<String> cars // 새 ... 생성
= new LinkedList<String>(); // ... LinkedList
cars.add("Ford"); // 객체 추가
cars.add("Mercedes");
String c = cars.get(1);
cars.set(1, "Toyota"); // 객체 교체
System.out.println(cars); // 리스트 출력
cars.remove(0); // 객체 제거
cars.clear(); // 전체 제거
cars.size(); // 길이 확인
[Ford, Toyota]
addFirst() 시작 위치에 추가addLast() 끝에 추가removeFirst() 시작에서 제거removeLast() 끝에서 제거cars.addFirst("Fiat"); // 맨 앞에 추가
cars.addLast("BMW"); // 맨 뒤에 추가
cars.removeFirst(); // 첫 객체 제거
cars.removeLast(); // 마지막 객체 제거
ArrayList와 LinkedList는 비슷해 보임ListArrayList와 LinkedList(또는 임의의 List)의 연산은 동일List를 쓸지는 용도에 따라 결정ArrayList 고려사항:list.get(11))
LinkedList 고려사항:list.get(11))
Java의 데이터 타입과 예외