Iterator, ListIterator, Enumeration


๐Ÿ”Ž Iterator, ListIterator, Enumeration


์ปฌ๋ ‰์…˜์— ์ €์žฅ๋œ ๋ฐ์ดํ„ฐ๋ฅผ ์ ‘๊ทผํ•˜๋Š”๋ฐ ์‚ฌ์šฉ๋˜๋Š” ์ธํ„ฐํŽ˜์ด์Šค

โ€ข Enumeration์€ Iterator์˜ ๊ตฌ๋ฒ„์ „์ด๋‹ค.

โ€ข ListIterator๋Š” Iterator์˜ ์ ‘๊ทผ์„ฑ์„ ํ–ฅ์ƒ์‹œํ‚จ ๊ฒƒ(์–‘๋ฐฉํ–ฅ)


Iterator ๋ฉ”์„œ๋“œ์„ค๋ช…
boolean hasNext()์ฝ์–ด ์˜ฌ ์š”์†Œ๊ฐ€ ๋‚จ์•„์žˆ๋Š”์ง€ ํ™•์ธ.
Object next()๋‹ค์Œ ์š”์†Œ๋ฅผ ์ฝ์–ด์˜จ๋‹ค.


Enumeration ๋ฉ”์„œ๋“œ์„ค๋ช…
boolean hasMoreElements()์ฝ์–ด ์˜ฌ ์š”์†Œ๊ฐ€ ๋‚จ์•„์žˆ๋Š”์ง€ ํ™•์ธ.
Object nextElemenet()๋‹ค์Œ ์š”์†Œ๋ฅผ ์ฝ์–ด์˜จ๋‹ค.


๐Ÿ”Ž Iterator


์ปฌ๋ ‰์…˜์— ์ €์žฅ๋œ ์š”์†Œ๋“ค์„ ์ฝ์–ด์˜ค๋Š” ๋ฐฉ๋ฒ•์„ ํ‘œ์ค€ํ™”ํ•œ ๊ฒƒ.

interface Iterator

public interface Iterator<E> {

	boolean hasNext();

	default void remove() {
		throw new UnsupportedOperationException("remove");
	}

	default void forEachRemaining(Consumer<? super E> action) {
		Objects.requireNonNull(action);
		while(hasNext())
			action.accept(next());	
	}
}


์‚ฌ์šฉ๋ฒ•

์‚ฌ์šฉ๋ฒ•์€ ์ปฌ๋ ‰์…˜์— iterator()๋ฅผ ํ˜ธ์ถœํ•ด์„œ Iterator๋ฅผ ๊ตฌํ˜„ํ•œ ๊ฐ์ฒด๋ฅผ ์–ป์–ด์„œ ์‚ฌ์šฉํ•œ๋‹ค.

List<Integer> list = new ArrayList<>();
Iterator it = list.iterator();

while(it.hasNext()) {
	System.out.println(it.next());
}


๐Ÿ”Ž Map๊ณผ Iterator


Map์—๋Š” Iterator()๊ฐ€ ์—†๋‹ค. (Iterator()๋Š” Collection ์ธํ„ฐํŽ˜์ด์Šค์— ์žˆ๋‹ค.)

๊ทธ๋ ‡๋‹ค๋ฉด Map์€ ์–ด๋–ป๊ฒŒ Iterator๋กœ ๋งŒ๋“ค์ˆ˜ ์žˆ์„๊นŒ??

์ •๋‹ต์€ ๋ฐ”๋กœ keySet(), entrySet(), values()๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด ๋œ๋‹ค!!!

๐Ÿ’ก ์˜ค๋Š˜ ์ฝ”๋”ฉํ…Œ์ŠคํŠธ ๋ฌธ์ œ์—์„œ ์ด ๋ถ€๋ถ„์ด ํ™œ์šฉ๋๋‹ค.

Iterator it = map.keySet().iterator();
Iterator it = map.entrySet().iterator();
Iterator it = map.values().iterator();