LinkedNestBlog

Iterator와 for 루프

by jinwon

Iterator와 for 루프 

 

출처 : http://benelog.springnote.com/pages/386996

 

List의 크기만큼 반복문을 도는 두 가지 방법

 

1. list.size()로 구한 크기만큼 for loop를 돌아 get(int index)로 List의 객체를 가져오는 방법

2. Iterator()로 java.util.Iterator 객체를 얻어 이 객체의 hasNext()가 true인 동안 반복문을 돌아 next()로 List의 객체를 가져오는 방법

 

객체가 arrayList 혹은 Vector인 경우 1번이 더 속도가 빠름.

> 이유는 ArrayList와 Vector가 RandomAccess 인터페이스를 구현하고 있기 때문.

 

그러나, List와 다른 Collection객체, 배열 등을 한꺼번에 묶어 처리할 때는 iterator pattern이 유용.