본문 바로가기

Java

for each 문에 대하여


iterator() 메소드가 존재하는 class는 모두 for each 문을 사용 할 수 있다.


다른말로 바꿔하면 어떤 class 던지 Iterable<T> 인터페이스를 구현(iterator() 메서드 구현)하였으면 for each 문을 사용 할 수 있다.


for each 문의 기본 사용법은 아래와 같다.

ArrayList<string> ar = new ArrayList<>();
ar.add("a");
ar.add("b");
ar.add("c");
		
for(String str: ar){
	System.out.println(str);
}




만약 어떤 class를 for each 문이 사용 가능한 class로 만들고 싶다면 아래와 같이 Iterable<T> 를 구현하면 된다.


public class StockBox implements Iterable<Stock>{
	private ArrayList<Stock> stockList = new ArrayList<>();  
	
	@Override
	public Iterator<Stock> iterator() {
		return this.stockList.iterator();
	}
	
	
	public StockBox(){
		this.stockList.add(new Stock("A", "DBC", 100));
		this.stockList.add(new Stock("A", "DBEX", 300));
		this.stockList.add(new Stock("B", "DBH", 70));
		this.stockList.add(new Stock("C", "DBS", 20));
	}
	
	public static void main(String[] args){
		StockBox sb = new StockBox();
		
		for(Stock s : sb){
			System.out.println(s.getName() + " (" + s.getGrade() + ") : " + s.getPrice());
		}
	}
}