J2SE 1.5 新功能特性:新的For循环(3)
2008-02-23 09:43:32来源:互联网 阅读 ()
- package java.lang;
- import java.util.Iterator;
- public interface Iterable<T> {
- Iterator<T> iterator();
- }
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:
- class Catalog implements Iterable<Product> {
- private List<Product> products = new ArrayList<Product>();
- void add(Product product) {
- products.add(product);
- }
- public Iterator<Product> iterator() {
- return products.iterator();
- }
- }
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:
- Catalog catalog = new Catalog();
- catalog.add(new Product("1", "pinto", new BigDecimal("4.99")));
- catalog.add(new Product("2", "flounder", new BigDecimal("64.88")));
- catalog.add(new Product("2", "cucumber", new BigDecimal("2.01")));
- for (Product product: catalog)
- product.discount(new BigDecimal("0.1"));
- for (Product product: catalog)
- 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
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash
