public class Demo {
public static void main(String[] args) {
Set set = new HashSet();//定义set集合
set.add("haha");//向set中添加数据
set.add("hehe");
set.add("hello");
//set遍历方法1
for (Object object : set) {
System.out.println(object);
}
System.out.println("----------");
//set遍历方法2;Iterator(迭代器)
for (Iterator iterator=set.iterator();iterator.hasNext();) {
String str=(String)iterator.next();
System.out.println(str);
}
System.out.println("-------");
Map map = new HashMap();//定义map集合
map.put("1", "haha");//map集合中添加元素
map.put("2", "hehe");
map.put("3", "hello");
//map遍历方法1
Set set1 = map.keySet();//将map中的key定义成set集合
for (Iterator iterator = set1.iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
String value = (String) map.get(key);
System.out.println(key + ":" + value);
}
System.out.println("--------");
//map遍历方法2
Set set2 = map.entrySet();//将map中的entry对象(键值对)定义成一个set集合
for (Iterator iterator = set2.iterator(); iterator.hasNext();) {
Map.Entry entry = (Entry) iterator.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println(key + ":" + value);
}
}
}