set

package net.jeongsam.collection;

public class PersonSet {
	private String name;
	private int age;
	
	public PersonSet(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public int getAge() {
		return age;
	}
	
	public void setAge(int age) {
		this.age = age;
	}
	
	@Override
	public boolean equals(Object o) {
		if (!(o instanceof PersonSet)) return false;
		if (((PersonSet)o).name.equals(name)
				&& ((PersonSet)o).age == age)
			return true;
		else
			return false;
	}
	
	@Override
	public int hashCode() {
		// 조슈아 블러시 방법
		int result = 17;
		result = 37 * result + name.hashCode();
		result = 37 * result + age;
		return result; 
	}
	
	@Override
	public String toString() {
		return super.toString() + " " + name + " " + age;
	}
}
package net.jeongsam.collection;

import java.util.*;

class HashSetEx03 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Set<PersonSet> personSet = new HashSet<PersonSet>();
		
		Collections.addAll(personSet,
				new PersonSet("이몽룡", 16),
				new PersonSet("성춘향", 16),
				new PersonSet("월매", 40),
				new PersonSet("이몽룡", 16)
				);
		
		for (PersonSet p : personSet)
			System.out.println(p);
		
		System.out.println(new PersonSet("이몽룡", 16).equals(new PersonSet("이몽룡", 16)));
	}

}

예제 9월 7일 Set의 사용

2009. 9. 7. 11:39
package net.jeongsam.collection;

import java.util.*;

class HashSetEx02 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Set<Integer> s1 = new HashSet<Integer>();
		
		/*
		s1.add(1);
		s1.add(3);
		*/
		
		Collections.addAll(s1, 10, 3, 5, 10, 7, 3, 8);
		
		System.out.println(s1);
		
		Set<String> s2 = new HashSet<String>();
		
		Collections.addAll(s2, "홍길동", "홍길동", "이몽룡");
		
		System.out.println(s2);
		
		// Foreach 문을 이용한 출력
		for (String e : s2)
			System.out.println(e);
		
		// Iterator 인터페이스 이용
		Iterator<String> i = s2.iterator();
		while (i.hasNext())
			System.out.println(i.next());
		
		// Set에 데이터 추가
		s2.add("성춘향");
		
		// Set에서 데이터 검색 : true or false 
		System.out.println(s2.contains("이몽룡"));
		
		// Set에서 집합 검색 : true of false
		Set<String> comp = new HashSet<String>();
		Collections.addAll(comp, "이몽룡", "성춘향", "홍길동");
		// Collections.addAll(comp, "월매", "성춘향");
		
		System.out.println(s2.containsAll(comp));
		
		// Set과 Set을 비교
		System.out.println(s2.equals(comp));
		
		// cf. ArrayList의 경우
		List<String> list1 = new ArrayList<String>();
		List<String> list2 = new ArrayList<String>();
		Collections.addAll(list1, "이몽룡", "성춘향", "홍길동");
		Collections.addAll(list2, "성춘향", "이몽룡", "홍길동");
		
		System.out.println(list1.equals(list2));
		
		// Set에서 특정 요소의 삭제
		System.out.println(s2.remove("홍길동") ? "삭제 성공" : "삭제 실패");
		System.out.println(s2);
	}
}

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) {
		List persons = 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을 상속받지 않았기 때문에 다음 메서드들은 사용할 수 없다.

[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의 초기값을 채움
		 */
		List persons =
			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 구현을 사용합니다.

5. Map

+ Recent posts