비선형 데이터구조, 해시(Hash) #10 Key 반복자

2021. 12. 9. 15:55DataStructure

이전글

https://yonghwankim-dev.tistory.com/179

 

비선형 데이터구조, 해시(Hash) #9 getValue & reSize 메서드

이전글 https://yonghwankim-dev.tistory.com/178 비선형 데이터구조, 해시(Hash) #8 add & remove 메서드 이전글 https://yonghwankim-dev.tistory.com/177 비선형 데이터구조, 해시(Hash) #7 재해싱 및 해시 클..

yonghwankim-dev.tistory.com

 

개요

이전글에서는 key값에 따른 value값을 반환하는 getValue 메서드와 해시 테이블에 데이터가 많이 저장되면 테이블의 크기를 증가시키는 reSize 메서드를 구현하였습니다. 이번글에서는 해시 테이블의 Key만을 추출하여 출력할 수 있도록 Key 반복자를 구현합니다.

 

1. IteratorHelper<T> 클래스 구현

IteratorHelper<T> 클래스는 Hash<K,V> 클래스의 내부 클래스로써 해시 테이블의 Key를 추출하는데 도와주는 클래스입니다.

class IteratorHelper<T>	implements Iterator<T>{
	T[] keys;
	int position;
				
	public IteratorHelper() {
		keys = (T[]) new Object[numElements];
		int p = 0;
			
		for(int i=0; i<tableSize;i++)
		{
			LinkedList<HashElement<K, V>> list = harray[i];
			for(HashElement<K, V> h : list)
			{
				keys[p++] = (T) h.key;
			}
		}
		position = 0;
	}

	@Override
	public boolean hasNext() {
		return position<keys.length;
	}

	@Override
	public T next() {
		if(!hasNext()) {
			return null;
		}
		return keys[position++];
	}
		
}

hasNext 메서드는 현재 position 변수가 keys 배열의 끝에 도달했는지 검사하는 메서드입니다. next 메서드는 keys 배열의 요소들을 반환합니다.

 

2. Hash 클래스의 iterate 메서드 구현

Hash 클래스에 IteratorHelper<T> 클래스 타입의 객체를 필드멤버로 선언하고 iterate 메서드에서 IteratorHelper<T> 생성자를 호출하여 초기화를 수행하고 현재 해시 테이블에 저장된 데이터들을 keys 배열에 저장합니다.

public class Hash<K, V>{
	...
	private IteratorHelper<K> iterator;
    
	public void iterate() {
		this.iterator = new IteratorHelper<K>();
		
		while(this.iterator.hasNext()) 
		{
			System.out.print(this.iterator.next()+" ");
		}
		System.out.println();
	}
}

 

3. Key 반복자 테스트

public static void main(String[] args) {
	Hash<String, Integer> hash = new Hash<String, Integer>(7);
	hash.add("a", 1);
	hash.add("b", 2);
	hash.add("c", 3);
	hash.add("d", 4);
	hash.add("e", 5);
	hash.add("f", 6);
	hash.add("g", 7);
	hash.add("h", 8); // reSize 수행
	hash.add("i", 9);
	hash.add("j", 10);
		
	hash.iterate();
}
b c d e f g h i j a

 

References

source code : https://github.com/yonghwankim-dev/DataStruct/tree/main/Hash/Implements
[부스트코스] 자바로 구현하고 배우는 자료구조