java

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;
	}
}
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);
	}
}
package net.jeongsam.collection;

import java.util.*;

class GenericEx01 {

	/**
	 * @param args
	 */
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		/*
		 * Java 1.4 이하 버전
		 */
		List l = new ArrayList();
		
		l.add("홍길동");
		l.add(new Integer(123));
		l.add(new Pet("토끼"));
		
		System.out.println((String)l.get(0));
		System.out.println(((Integer)l.get(1)).intValue());
		System.out.println(((Pet)l.get(2)).getName());
		
		/*
		 * Java 5.0 이상
		 */
		
		List<String> generL = new ArrayList<String>();
		
		generL.add("홍길동");
		generL.add("홍진성");
		
		System.out.println(generL.get(0));
		System.out.println(generL.get(1));
		
		List<Integer> generInt = new ArrayList<Integer>();
		
		// Auto boxing
		/*
		 * Integer i = new Integer(100); // Wrapper Class 이용하여 객체로 boxing
		 * generInt.add(i); // 객체를 ArrayList에 추가
		 */
		generInt.add(100);
		generInt.add(200);

		// Unboxing
		/*
		 * Integer i = (Integer)generInt.get(0); // Down casting하여
		 *                              // Object 타입을 Integer 타입으로 변경
		 * System.out.println(i.intValue()); // 객체에서 원시타입 꺼냄
		 */
		System.out.println(generInt.get(0));
		System.out.println(generInt.get(1));
	}

}

Collection 계층의 인터페이스들

컬렉션 인터페이스들

1. Collection 인터페이스

Collection 인터페이스는 Set과 List 등을 대표합니다. Collection에서 정의된 공통적인 메서드들은 Collection을 상속받은 하위 인터페이스들이 일반적으로 가지는 메서드들을 대부분 정의하고 있기 때문에 하위 인터페이스의 유형과 상관없이 다목적으로 생성자를 이용하여 초기화할 수 있습니다. 프로그래머는 이러한 성질을 이용하여 하위 인터페이스 타입에 대해 자유로운 작업 가능합니다.

package net.jeongsam.collection;

import java.util.*;

class CollectionEx01 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Collection l = new ArrayList();
		Collection s = new HashSet();
		Iterator i;
		
		/*
		 * Collections.addAll(Collection<? super string> c, String... elements)
		**/
		Collections.addAll(l, "성진", "육관대사", "진채봉", "계섬월", "성진", "정경패", "성진", 
				"가춘운", "적경홍", "이소화", "심요연", "백능파");
		
		/*
		 * for (Object o : Collection c)
	     *     System.out.println(o);
		**/
		System.out.println("--- ArrayList 출력 (foreach) ---");
		for (String e : l)
			System.out.println(e);
		
		System.out.println("--- ArrayList 출력 (Iterator) ---");
		i = l.iterator();
		while (i.hasNext())
			System.out.println(i.next());
		
		Collections.addAll(s, "성진", "육관대사", "진채봉", "계섬월", "성진", "정경패", "성진", 
				"가춘운", "적경홍", "이소화", "심요연", "백능파");
		
		System.out.println("--- HashSet 출력 (foreach) ---");
		for (String e : s)
			System.out.println(e);
		
		System.out.println("--- HashSet 출력 (Iterator) ---");
		i = s.iterator();
		while (i.hasNext())
			System.out.println(i.next());
	}
}
[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에 저장된 요소를 배열로 리턴한다.

2. Set 인터페이스

Set은 중복을 허용하지 않는 Collection의 하위 타입입니다. Set 인터페이스는 Collection으로부터 상속받은 메서드들만을 포함하고 중복을 허용하지 않는 선에서 메서들을 추가합니다. 예를 들어 List의 add() 메서드의 경우 중복을 허용하여 Collection의 add()를 구현하지만 Set의 add() 메서드는 중복을 허용하지 않도록 구현됩니다. 그리고 List의 경우 '인덱스'를 기준으로 추가되지만 Set의 경우 '값'을 기준으로 존재 유무가 결정되기 때문에 인덱스 개념이 없습니다.

Set의 저장순서는 List와는 다릅니다. Integer와 String처럼 미리 사용할 수 있도록 정의된 타입이 아닌 자신만의 타입을 정의하였을 경우 저장 순서를 유지하기 위해 Set을 구현한 클래스에 따라 필요한 구현을 추가로 해야합니다.

타입 설명
Set(인터페이스) Set에 저장되는 각각의 값들은 고유해야하고 중복된 값은 저장되지 않습니다. Set에 저장되는 요소는 반드시 객체의 동일성을 판별하기 위해 equals() 메서드를 정의해야 합니다. Set은 Collection을 상속받았지만 요소의 순서를 보장하지는 않습니다.
HashSet 빠른 검색을 보장해주며 HashSet에 저장되는 각 요소는 equals()와 hashCode()를 구현해야 합니다.
TreeSet 트리 구조의 순서를 가지는 Set으로 정렬된 요소를 얻어낼 수 있습니다. Comparable 인터페이스를 구현해야 합니다.
LinkedHashSet HashSet의 검색 속도와 List의 특징인 순서를 유지하는 Set으로 추가된 순서로 Set을 탐색할 수 있습니다. hashCode()를 구현해야 합니다.
package net.jeongsam.collection;

public class CarSet {
	private String name;
	private int id = 0;
	
	public CarSet(String name) {
		this.name = name;
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public boolean equals(Object o) {
		boolean isEqual = false;
		if ((o instanceof CarSet) && ((CarSet)o).name.equals(name)) {
			isEqual = true;
		}
		
		return isEqual;
	}
	
	/*
	 * Set 인터페이스에서 구현해야 하는 메서드
	 */
	@Override
	public int hashCode() {
		// Joshua Bloch의 작성법을 사용
		int result = 17;
		result = 37 * result + name.hashCode();
		result = 37 + result + id;
		return result;
	}
	
	/*
	 * HashSet 인터페이스에서 구현해야 하는 메서드
	 */
	@Override
	public String toString() {
		return name + " " + hashCode();
	}
}
package net.jeongsam.collection;

import java.util.*;

class SetEx02 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Set cars = new HashSet();
		
		cars.add(new CarSet("소나타"));
		cars.add(new CarSet("그랜저"));
		cars.add(new CarSet("무쏘"));
		cars.add(new CarSet("소나타"));
		cars.add(new CarSet("제니스"));
		
		for (CarSet car : cars)
			System.out.println(car);
		
		System.out.println(new CarSet("소나타").equals(new CarSet("소나타")));
	}

}

3. List 인터페이스

List는 저장 순서대로 요소들을 유지하고 관리한다. List는 두가지 형식을 제공합니다.

  • ArrayList와 Vector는 요소들을 인덱스를 이용하여 무작위로 액세스하는데는 좋은 성능을 발휘하지만 List의 중간에 요소들을 추가하거나 삭제시는 느리다.
  • LinkedList는 순차적인 액세스에 좋은 성능을 발휘하고 List의 중간에 요소를 추가하거나 삭제시도 좋은 성능을 발휘한다.
package net.jeongsam.collection;

import java.util.*;

class ListEx01 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		List pets = new ArrayList();
		List compPets = new ArrayList();
		List lPets = new LinkedList();
		ListIterator listPets;
		
		Collections.addAll(pets, new Pet("강아지"), new Pet("고양이"), new Pet("거북이"));
		Collections.addAll(lPets, new Pet("강아지"), new Pet("고양이"), new Pet("거북이"));
		Collections.addAll(compPets, new Pet("강아지"), new Pet("거북이"));
		
		System.out.println(pets.contains(new Pet("강아지")));
		System.out.println(pets.containsAll(compPets));
		
		System.out.println(pets);
		
		// LinkedList에서만 가능한 메서드
		((LinkedList)lPets).addFirst(new Pet("거북이"));
		System.out.println(lPets);
		System.out.println(((LinkedList)lPets).getLast());
		
		// 얕은 복사 실행 : 객체의 참조를 복사함
		listPets = lPets.listIterator();
		listPets.add(new Pet("이구아나"));
		listPets.previous();
		while (listPets.hasNext()) {
			System.out.print(listPets.next() + " ");
		}
		System.out.println();
		System.out.println(lPets);
	}

}

3. Iterator

List와 Set을 범용적으로 읽어낼 수 있는 인터페이스로 컬렉션을 순차적으로 출력할 때 사용합니다. Collection 인터페이스는 Iterable 인터페이스을 상속받아 iterator() 메서드를 통해 Iterator 인터페이스를 간접적으로 구현해냅니다. 보통 Collection 인터페이스를 구현한 컬렉션들은 iterator() 메서드를 이용하여 Iterator 인터페이스의 순차 접근 방식을 사용하여 요소에 접근하거나 foreach 문을 통해 접근할 수 있습니다.

4. Map 인터페이스

Map은 키와 값을 쌍으로 같는 요소들의 집합입니다. 키는 중복을 허용하지 않으며 키를 이용하여 값에 접근할 수 있습니다.

package net.jeongsam.collection;

import java.util.*;

class MapEx01 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Map<String, String> m = new HashMap<String, String>();
		
		m.put("바둑이", "세퍼드");
		m.put("똘이", "세퍼드");
		
		System.out.println(m);
		System.out.println(m.get("바둑이"));
	}

}

+ Recent posts