J2SE 1.5 新功能特性:新的For循环(3)

2008-02-23 09:43:32来源:互联网 阅读 ()

新老客户大回馈,云服务器低至5折



  1. package java.lang;
  2. import java.util.Iterator;
  3. public interface Iterable<T> {
  4. Iterator<T> iterator();
  5. }


To implement this interface in Catalog, you must code an iterator method. This method must return an Iterator object that is bound to the Product type.

The Catalog class stores all of its Product objects in an ArrayList. The easiest way to provide an Iterator object to a client is to simply return the Iterator object from the products ArrayList itself. Here is the modified Catalog class:

  1. class Catalog implements Iterable<Product> {
  2. private List<Product> products = new ArrayList<Product>();
  3. void add(Product product) {
  4. products.add(product);
  5. }
  6. public Iterator<Product> iterator() {
  7. return products.iterator();
  8. }
  9. }


Note that the Iterator, the List reference, and the ArrayList are all bound to the Product type.

Once you have implemented the java.lang.Iterable interface, client code can use the foreach loop. Here is a bit of example code:
  1. Catalog catalog = new Catalog();
  2. catalog.add(new Product("1", "pinto", new BigDecimal("4.99")));
  3. catalog.add(new Product("2", "flounder", new BigDecimal("64.88")));
  4. catalog.add(new Product("2", "cucumber", new BigDecimal("2.01")));
  5. for (Product product: catalog)
  6. product.discount(new BigDecimal("0.1"));
  7. for (Product product: catalog)
  8. System.out.println(product);



Summary


The foreach loop provides a simple, consistent solution for iterating arrays, collection classes, and even your own collections. It eliminates much of the repetitive code that you would otherwise require. The foreach loop eliminates the need for casting as well as some potential problems. The foreach loop is a nice new addition to Java that was long overdue. I greatly appreciate the added simplicity in my source code.

Trying it Out


You can download the current beta version of J2SE 1.5 from Sun's Web site.

上一篇: J2SE 1.5 中的Formatter 类
下一篇: j2se1.4 与 j2se5.0(图)

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:20分钟熟悉猛虎脾气-JDK1.5新特性介绍

下一篇:闲来无事,写了个删除文件夹的java类