ArrayList
-
예제 9월 7일 ArrayList와 Vector의 사용2009.09.07
-
[Java강의노트] 컨테이너를 이용한 자료구조 관리하기2009.09.04
예제 9월 7일 ArrayList와 Vector의 사용
package net.jeongsam.collection; import java.util.*; class ListEx02 { public static void main(String[] args) { /* * ArrayList와 Vector의 선언 */ List<String> strArrayList = new ArrayList<String>(5); List<String> strVector = new Vector<String>(5, 5); /* * List에 요소 추가하기 */ strArrayList.add("홍길동"); strVector.add("홍길동"); /* * List의 크기 구하기 */ System.out.println(strArrayList.size()); System.out.println(strVector.size()); // Vector의 메모리 할당량 System.out.println( ((Vector<String>)strVector).capacity()); /* * Collections.addAll() 이용한 추가 */ Collections.addAll(strArrayList, "이몽룡", "성춘향", "월매", "변악도", "향단이", "방자"); Collections.addAll(strVector, "이몽룡", "성춘향", "월매", "변악도", "이몽룡", "향단이", "방자"); /* * index를 이용한 요소 읽어오기 */ System.out.println( ((ArrayList<String>)strArrayList).get(2)); System.out.println( ((Vector<String>)strVector).elementAt(2)); // Vector에서 첫번째 요소 읽기 System.out.println( ((Vector<String>)strVector).firstElement()); System.out.println( ((Vector<String>)strVector).indexOf("이몽룡")); // Vector에서 마지막 요소 읽기 System.out.println( ((Vector<String>)strVector).lastElement()); System.out.println( ((Vector)strVector).lastIndexOf("이몽룡")); // ArrayList와 Vector에 포함된 요소의 개수 알아내기 System.out.println(searchCount(strArrayList, "이몽룡")); System.out.println(searchCount(strVector, "이몽룡")); } public static int searchCount(Collection<String> c, String s) { Iterator<String> i = c.iterator(); int count = 0; while (i.hasNext()) { if (i.next().equals(s)) count++; } return count; } }
[Java강의노트] 컨테이너를 이용한 자료구조 관리하기
Collection 컨테이너들
객체를 저장하기 위해 Java는 java.util 패키지에 List, Set, Queue, Map의 기본 인터페이스 세트를 준비하고 있습니다. 그 중 List와 Set의 경우 Collection을 상속 받아 작성된 인터페이스입니다. 각 세트는 서로 다른 특성을 가지고 있는데 List의 경우 배열과 비슷한 구조를 가지고 있으며 배열이 고정된 크기를 가지는데 반해서 List는 가변적인 크기를 지원합니다. Set은 중복되지 않는 유일한 값을 저장하며 Map은 객체를 다른 객체와 연관시킬 수 있는 연관 배열과 비슷한 구조를 갖습니다. 이 List와 Set, Map 인터페이스를 구현하여 다양한 자료 구조를 조작할 수 있는 클래스들이 제공됩니다.
1. Collections
Arrays가 배열을 대상으로 한 작업 유틸리티라면 Collections는 객체 리스트를 대상으로 한 유틸리티라고 할 수 있습니다. Arrays.fill() 메서드가 배열에 특정 초기값을 채우는 역할을 하는 것과 마찬가지로 Collections.fill() 메서드 역시 List 객체에 국한되나 객체 리스트에 특정 초기값을 채우는 기능을 합니다.
package net.jeongsam.collection; class Person { private String name; public Person(String name) { this.name = name; } public void setName(String name) { this.name = name; } public String toString() { return super.toString() + " " + name; } }
package net.jeongsam.collection; import java.util.ArrayList; import java.util.Collections; import java.util.List; class FillToList { /** * Person 객체를 요소로 갖는 ArrayList를 특정 값으로 채움 */ public static void main(String[] args) { Listpersons = new ArrayList ( /* 7개의 Person 타입의 동일한 객체로 복제하여 리스트를 채움 */ Collections.nCopies(7, new Person("홍길동"))); /* 동일한 객체이므로 한 객체의 멤버변수 값을 변경하면 리스트내의 모든 객체에 영향을 준다. */ Person p = persons.get(0); p.setName("변학도"); System.out.println(persons); /* 리스트의 모든 요소를 Person 타입의 동일한 객체로 복제하여 채움 */ Collections.fill(persons, new Person("무명씨")); System.out.println(persons); } }
2. Collection
Set과 List는 Collection을 상속받았기 때문에 다음 메서드를 제공한다. Map의 경우 Collection을 상속받지 않았기 때문에 다음 메서드들은 사용할 수 없다.
메서드 | 설명 |
---|---|
boolean add(T) | T 타입의 객체를 추가한다. |
boolean addAll(Collection<? extends T>) | 현재 Collection에 매개변수로 지정된 Collection의 모든 요소를 추가한다. |
void clear() | Collection이 보관하고 있는 모든 요소를 제거한다. |
boolean contains(T) | T 타입의 객체를 가지고 있으면 true를 리턴한다. |
boolean containsAll(Collection<?>) | 매개변수로 지정된 Collection의 모든 요소를 가지고 있으면 true를 리턴한다. |
boolean isEmpty() | Collection이 비어 있으면 true를 리턴한다. |
Iterator<T> iterator() | Collection에 저장된 요소를 순차 접근이 가능한 Iterator 타입의 리스트로 리턴한다. |
boolean remove(Object) | Collection에 저장된 요소 중 Object에 해당되는 객체를 하나 삭제한다. |
boolean removeAll(Collection<?>) | 현재 Collection에 저장된 요소 중 매개변수로 전달된 Collection에 포함된 요소를 삭제한다. |
boolean remainAll(Collection<?>) | 현재 Collection에 저장된 요소 중 매개변수로 전달된 Collection에 포함된 요소만 남기도 나머지를 삭제한다. |
int size() | 현재 Collection에 저장된 요소의 개수를 리턴한다. |
Object[] toArray() | 현재 Collection에 저장된 요소를 배열로 리턴한다. |
3. List
List의 경우 객체를 저장하는 가변 크기의 배열이며 다음과 같이 생성할 수 있습니다.
List<Person> persons = new ArrayList<Person>();
리스트에 객체를 추가하기 위하여 앞서 살펴본 Collections를 사용할 수 있다.
package net.jeongsam.collection; import java.util.*; public class AddList { /** * @param args */ public static void main(String[] args) { /* * Arrays.toList() 메서드를 이용하여 ArrayList의 초기값을 채움 */ Listpersons = new ArrayList (Arrays.asList(new Person("홍길동"), new Person("이몽룡"), new Person("변악도"))); persons.add(new Person("성춘향")); // ArrayList는 가변형 배열 구조이므로 추가 가능 persons.addAll(Arrays.asList(new Person("홍길동"), new Person("이몽룡"), new Person("변악도"))); /* * Arrays.asList() 메서드를 이용하여 List를 직접 채움 */ persons = Arrays.asList(new Person("홍길동"), new Person("이몽룡"), new Person("변악도")); //persons.add(new Person("성춘향")); // 실행시 UnsupportedOperationException 예외발생. // 배열은 고정 크기를 가지므로 List.add()불가 for (Person p : persons) { System.out.println(p); } /* * Collection.addAll() 메서드를 사용하여 List를 채움 */ Collection cPersons = new ArrayList (); Person[] arrPersons = {new Person("홍길동"), new Person("이몽룡"), new Person("변악도")}; cPersons.addAll(Arrays.asList(arrPersons)); cPersons.add(new Person("성춘향")); for (Person p : cPersons) { System.out.println(p); } /* * Collections.addAll() 메서드를 이용하여 List를 채움 */ Collections.addAll(cPersons, new Person("홍길동"), new Person("이몽룡"), new Person("변악도")); /* 배열을 이용하여 List를 채움 */ Collections.addAll(cPersons, arrPersons); for (Person p : persons) { System.out.println(p); } /* * Iterator 인터페이스를 이용하여 List 출력 */ Iterator iPersons = persons.iterator(); while (iPersons.hasNext()) { Person p = iPersons.next(); System.out.println(p); } } }
4. Set
Set은 중복되는 객체를 허용하지 않습니다. 주로 주어진 객체의 존재 유무를 검색하는 용도로 사용됩니다. 일반적으로 빠른 검색에 최적화되어 있는 HashSet 구현을 사용합니다.