[java] 增强的for语句

  • Enhanced for语句可以方便地处理数组、集合中各元素
  • 如:
    int[] ages = new int[10];
    for(int age : ages)
    {
    ` System.out.println(age); }`
  • 这种语句是只读式的遍历

遍历链表

  • enhanced-for语句可以使编译器生成Iterator的while(hasNext()){…next()}
  • 例如
    Iterator<Photo> iterator = album.iterator();
    while(iterator.hasNext()){
    Photo photo = iterator.next();
    System.out.println(photo.toString());
    }
    

    相当于

    for(Photo photo : album){
    System.out.println(photo);
    }
    
Written on December 1, 2022