盘点JDK1.5的新特性(三)——加强for循环

来源:互联网 发布:研究生知行论坛 编辑:程序博客网 时间:2024/05/18 03:39
接着上篇文章来写,其实加强for循环现在用过的人很多,上篇文章中我就已经用到了
public static int add(int i,int... js){          for(int j : js)              i += j;          return i;      }  

这里再做一个总结,首先解释一下加强for循环:J2SE 1.5提供了另一种形式的for循环。借助这种形式的for循环,可以用更简单地方式来遍历数组和Collection等类型的对象。所谓的加强for循环就是其他语言中的foreach,在java中可以通过这种方式来遍历容器和数组中的数据。

具体的说能够使用加强for循环遍历的可以归纳为两种:

  1. 数组
  2. 所有实现了Iterable接口的类,JDK的API中给了下面一个列表
    接口 Iterable<T>所有已知子接口: BeanContext, BeanContextServices, BlockingDeque<E>, BlockingQueue<E>, Collection<E>, Deque<E>, List<E>, NavigableSet<E>, Queue<E>, Set<E>, SortedSet<E> 所有已知实现类: AbstractCollection, AbstractList, AbstractQueue, AbstractSequentialList, AbstractSet, ArrayBlockingQueue, ArrayDeque, ArrayList, AttributeList, BatchUpdateException, BeanContextServicesSupport, BeanContextSupport, ConcurrentLinkedQueue, ConcurrentSkipListSet, CopyOnWriteArrayList, CopyOnWriteArraySet, DataTruncation, DelayQueue, EnumSet, HashSet, JobStateReasons, LinkedBlockingDeque, LinkedBlockingQueue, LinkedHashSet, LinkedList, PriorityBlockingQueue, PriorityQueue, RoleList, RoleUnresolvedList, RowSetWarning, SerialException, ServiceLoader, SQLClientInfoException, SQLDataException, SQLException, SQLFeatureNotSupportedException, SQLIntegrityConstraintViolationException, SQLInvalidAuthorizationSpecException, SQLNonTransientConnectionException, SQLNonTransientException, SQLRecoverableException, SQLSyntaxErrorException, SQLTimeoutException, SQLTransactionRollbackException, SQLTransientConnectionException, SQLTransientException, SQLWarning, Stack, SyncFactoryException, SynchronousQueue, SyncProviderException, TreeSet, Vector 

    可以看到常用的Collection,List,Queue,Set接口也都实现了Iterable接口,同理他们的所有子类都可以利用加强for循环来进行遍历,具体例子已经很简单就不多说了,这里要强调的是,加强for循环遍历其实是利用了底层的iterator迭代器,也就是说下面两段代码实际上是一样的
    List<Integer> list = new ArrayList<Integer>();list.add(1);list.add(2);list.add(3);for(int i : list){    System.out.println(i);}
    List<Integer> list = new ArrayList<Integer>();list.add(1);list.add(2);list.add(3);Iterator<Integer> iterator = list.iterator();while(iterator.hasNext()){System.out.println(iterator.next());}

    所以在调用加强for循环的时候一定要注意所遍历对象的iterator