1.1 遍历集合的几种方式
- 使用迭代器Iterator的方式
- 使用增强for循环的方式
- 常用的for循环
1.2 遍历数组
public static void main(String[] args) {
String[] arr = new String[] { "xx", "yy", "zz" };
for (String elt : arr) {
System.out.println(elt);
}
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
1.3 遍历List
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("aa");
list.add("bb");
list.add("cc");
for (String elt : list) {
System.out.println(elt);
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
for (Iterator<String> iter = list.iterator(); iter.hasNext();) {
String elt = iter.next();
System.out.println(elt);
}
}
1.4遍历Set
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
set.add("dd");
set.add("ee");
set.add("ff");
for (String elt : set) {
System.out.println(elt);
}
for(Iterator<String> iter = set.iterator(); iter.hasNext() ; ){
String elt = iter.next();
System.out.println(elt);
}
}
1.5遍历Map
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("aa", "xx");
map.put("bb", "yy");
map.put("cc", "zz");
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry);
}
for(String key : map.keySet()){
System.out.println(key + " = " + map.get(key));
}
for(String value : map.values()){
System.out.println(value);
}
}