分享
 
 
 

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

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

By Jeff Langr

Like many Java developers you are probably working with the beta for J2SE 1.5. Here is another new technique to use with the beta. Looping through a collection of objects and doing something with each object is one of the most common programming idioms. You've no doubt coded such a loop many times:

List names = new ArrayList(); names.add("a"); names.add("b"); names.add("c"); for (Iterator it = names.iterator(); it.hasNext(); ) { String name = (String)it.next(); System.out.println(name.charAt(0)); }

Instead of using a for loop, you might have used a while loop. You might have used an Enumeration, instead of an Iterator, if you were working with the older Vector class. Or, you might have used a for loop and a counter, accessing each element using the get(int index) method of the List interface.

If you were to use an array, this is how you would typically iterate through each of its elements:

String[] moreNames = { "d", "e", "f" }; for (int i = 0; i < moreNames.length; i++) System.out.println(moreNames[i].charAt(0));

It's not difficult to iterate through a collection, but it is a very repetitive operation. Iteration requires you to type a good amount of characters. Granted, the template feature of most IDEs will eliminate your need to type so much. But, as you saw, there are many ways to iterate through a loop.

The existence of several different iteration techniques costs you more time. For each iteration you encounter, you must spend a few extra seconds digesting the iteration form. If it deviates from the form you're used to seeing, you must examine it even closer. Why did the developer choose to code the iteration differently?

It's also easy to make a mistake in coding your iterator. Ever accidentally coded something like this?

List names = new ArrayList(); names.add("a"); names.add("b"); names.add("c"); for (Iterator it = names.iterator(); it.hasNext(); ) { String name = (String)it.next(); System.out.println(((String)it.next()).charAt(0)); }

I have. In a small section of code, it's easy to spot the error. In a larger section of code, it's not as easy to spot.

The foreach Loop

Java 1.5 introduces a new way of iterating over a collection of objects. The foreach loop is also known as the enhanced for loop. It is a new syntactical construct designed to simplify iteration. The foreach loop should make iteration more consistent, but only if and when everyone starts using it.

Effective use of the foreach loop depends on using Java 1.5's parameterized types, also known as generics. So that you can understand the code in this article, I'll explain how to use parameterized types.

Here is how you might construct and iterate a list of names in Java 1.5:

List<String> names = new ArrayList<String>();

names.add("a");

names.add("b");

names.add("c");

for (String name: names)

System.out.println(name.charAt(0));

There are two important things in this bit of code: first, the use of a generic list, and second, the use of the new foreach loop.

To construct an object of the parameterized ArrayList type, you bind the ArrayList to a class. In the example, you bind the ArrayList to the String class. You also bind the List reference to the String class. You are now restricted to adding only String objects to the list. If you insert, for example, a Date object in the names collection, your code will not compile. When you retrieve objects from the list, you need not cast. Java knows that the list contains only String objects. It does the casting for you, behind the scenes.

Once you have stored objects in a parameterized List, you can iterate through them using the foreach loop:

for (String name: names)

You read this statement as, "for each String name in names." The Java VM executes the body of the foreach loop once for each object in the names collection. Each time through the loop, Java assigns the next object in turn to a local reference variable called name. You must declare this reference variable as a String type--the type to which you bound the names collection.

The foreach loop is succinct. There is no need to cast; Java does the cast for you. You can use the name reference within the body of the loop as a String reference. You cannot use the name reference outside the body of the foreach loop.

Using Foreach with Arrays

You saw how the foreach loop allows you to iterate over collection class types. Sun also modified Java to allow you to iterate through arrays using foreach. The syntax is exactly the same:

String[] moreNames = { "d", "e", "f" }; for (String name: moreNames) System.out.println(name.charAt(0));

Supporting Foreach in Your Own Class

Suppose you are building a Catalog class. A Catalog object collects any number of Product objects. You store these objects using an ArrayList instance variable defined in Catalog. Code working with a Catalog object will frequently need to iterate through the entire list of products, to do something with each object in turn.

Here is how the Catalog class might look:

import java.util.*; class Catalog { private List<Product> products = new ArrayList<Product>(); void add(Product product) { products.add(product); } }

The Product class includes a method that allows you to discount the price on a product:

class Product { private String id; private String name; private BigDecimal cost; Product(String id, String name, BigDecimal cost) { this.id = id; this.name = name; this.cost = cost; } void discount(BigDecimal percent) { cost = cost.multiply(new BigDecimal("1.0").subtract(percent)); } public String toString() { return id + ": " + name + " @ " + cost; } }

A (Poor) Solution

To allow client code to work with all products, you could create a method in Catalog that returned the ArrayList of products:

// don't do this List<Product> getProducts() { return products; }

Client code could iterate through the list however they chose. However, returning a collection to a client is a bad idea. By giving the client your collection, you have relinquished any control over the contents of that collection. Client code could add or remove elements to the collection without the knowledge of the Catalog object. You've also burdened the client with more work than necessary.

The Iterable Interface

Instead, you can designate the Catalog class as being "iterable." Making a class iterable tells clients that they can iterate through its contents using a foreach loop. Sun has added to Java a new interface, java.lang.Iterable, that allows you to mark your classes as iterable:

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.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有