본문 바로가기

자바

30. Java Collection2

맵은 키와 값으로 이루어진 자료구조다. 키는 반드시 유일해야 한다. 키를 이용하여 값에 접근하는 방식으로 작동한다. 

package com.MapCollection;

import java.util.HashMap;
import java.util.Iterator;

public class HowToUseMap {
	public static void main(String[] args) {
		HashMap<Integer, String> hm = new HashMap<Integer, String>();
		
		//해당 key에 대한 value 삽입
		hm.put(0, "str0");
		hm.put(1, "str1");
		hm.put(2, "str2");
		hm.put(3, "str3");
		hm.put(4, "str4");
		System.out.println(hm.toString());
		
		hm.remove(2); //key 2 삭제
		System.out.println(hm.toString());
		
		hm.clear(); //맵 초기화
		System.out.println(hm.toString());
		
		hm.put(0, "str0");
		hm.put(1, "str1");
		hm.put(2, "str2");
		hm.put(3, "str3");
		hm.put(4, "str4");
		System.out.println(hm.toString());
		
		//map의 iterator(반복자)를 선언
		Iterator<Integer> iterator = hm.keySet().iterator();
		while(iterator.hasNext()) { //원소를 끝까지 출력
			System.out.println(hm.get(iterator.next()));
		}
	}
}

 

 

셋은 유일한 데이터를 가지고 있는 자료구조다. 자료의 중복을 허락하지 않는다. 셋은 자료의 순서가 없다.

package com.HashSet;

public class Student {
	private String name;
	private int grade;
	
	public Student(String name, int grade) {
		this.name=name;
		this.grade=grade;
	}
	
	public String toString() {
		return name + " : " + grade;
	}
	
	//이 밑으로 삭제하면 원소 삭제 안됨
	public boolean equals(Object obj) {
		String compareValue = obj.toString();
		String thisValue = toString();
		return thisValue.equals(compareValue);
	}
	
	public int hashCode( ) {
		return toString().hashCode();
	}
}

 

package com.HashSet;

import java.util.HashSet;
import java.util.Iterator;

public class HowToUseSet {
	public static void main(String[] args) {
		HashSet<String> st = new HashSet<String>();
		
		//셋에 값을 입력
		st.add("str0");
		st.add("str1");
		st.add("str2");
		st.add("str3");
		st.add("str4");
		System.out.println(st.toString());
		
		st.remove("str0"); //원소 삭제
		System.out.println(st.toString());
		
		st.clear();
		System.out.println(st.toString());
		
		st.add("str0");
		st.add("str1");
		st.add("str2");
		st.add("str3");
		st.add("str4");
		
		//set의 이터레이터를 선언
		Iterator<String> iterator = st.iterator();
		while(iterator.hasNext()) { //원소의 끝까지 출력, 순서를 무시
			System.out.println(iterator.next());
		}
		
		HashSet<Student> studentSet = new HashSet<Student>();
		
		studentSet.add(new Student("한상욱", 1));
		studentSet.add(new Student("김민석", 2));
		studentSet.add(new Student("기모띠", 3));
		
		Student student = new Student("한상욱", 1);
		
		//클래스 안에 equals와 hashCode 오버라이딩 한 것을 삭제하면 삭제 안됨(remove로 객체 기준에 set을 삭제할 시 주소값을 이용하여 삭제하므로)
		studentSet.remove(student); 
		
		System.out.println(studentSet.toString());
		
	}
}

 

Iterator는 데이터를 반복적으로 검색하는데 유용한 인터페이스다 모든 자료구조는 이터레이터를 지원한다.

'자바' 카테고리의 다른 글

32. 쓰레드  (0) 2019.08.21
31. Java 입출력(I/O)  (0) 2019.08.19
29. Java collection1  (0) 2019.08.12
28. 예외 처리  (0) 2019.08.11
27. API(StringTokenizer)  (0) 2019.08.08