[JAVA] Iterator, for문 map,list,hashmap 기본활용방법
Iterator, for문 map,list,hashmap 기본활용방법
iterator에 대해서 궁금해서 찾아봤는데 반복자라는 뜻이며 for문보다 간단히 활용할수 있을것 같아
for문과 함께 비교해서 사용을 아래와 같이 해보았다.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class foreach {
public static void main(String[] args) {
//1. Map
Map<Object, String> map1 = new HashMap<Object, String>();
map1.put("1", "One");
map1.put("2", "Two");
map1.put("3", "Three");
//2. ArrayList
ArrayList<String> list1 = new ArrayList<String>();
list1.add("One");
list1.add("Two");
list1.add("Three");
//3. HashMap
HashMap<Object, String> map2 = new HashMap<Object, String>();
map2.put("1", "One");
map2.put("2", "Two");
map2.put("3", "Three");
//1
Iterator it = map1.keySet().iterator();
//2
Iterator it2 = list1.iterator();
//3
Iterator it3 = map2.values().iterator();
System.out.println("== while 문 활용==");
//1
while(it.hasNext()){
String key = (String) it.next();
System.out.println(key);
}
//2
while(it2.hasNext()){
String value = (String) it2.next();
System.out.println(value);
}
//3
while(it3.hasNext()){
String value = (String) it3.next();
System.out.println(value);
}
System.out.println("== For문 활용 ==");
//1
for(Object key : map1.keySet()){
System.out.println("key : " + key +" / value : " + map1.get(key));
}
//2
for(int i=0; i<list1.size(); i++){
System.out.println(list1.get(i).toString());
}
//3
for(Object key : map2.keySet()){
System.out.println("key : " + key +" / value : " + map2.get(key));
}
}
}