Home  >  Article  >  Java  >  Analysis of several usages of Java for loop

Analysis of several usages of Java for loop

高洛峰
高洛峰Original
2017-01-21 16:09:101357browse

J2SE 1.5 provides another form of for loop. With this form of for loop, objects of types such as arrays and Collections can be traversed in a simpler way. This article introduces specific ways to use this loop, explains how to define your own classes that can be traversed in this way, and explains some common problems with this mechanism.

In a Java program, when you want to "process" - or "traverse" - the elements in an array or Collection one by one, you will usually use a for loop to achieve this (of course, use other Various types of loops are not impossible, but I don’t know whether it is because the length of the word for is relatively short, or because the meaning of the word for is more suitable for this kind of operation. In this case, the for loop is much more commonly used than other loops).

For traversing arrays, this loop is generally written like this:

List 1: Traditional way of traversing arrays

 /* 建立一个数组 */
 int[] integers = {1, 2, 3, 4};
 /* 开始遍历 */
 for (int j = 0; j 8b6539a4dcc116553d9bd871a8d36ba1 strings = new ArrayList10561f52a538bad7dc0ea5defc38baab();<br> strings.add("A");<br> strings.add("B");<br> strings.add("C");<br> strings.add("D");<br> for (String str : integers) {<br>     System.out.println(str); /* 依次输出“A”、“B”、“C”、“D” */<br> }<p><br></p><p>循环变量的类型可以是要被遍历的对象中的元素的上级类型。例如,用int型的循环变量来遍历一个byte[]型的数组,用Object型的循环变量来遍历一个Collection10561f52a538bad7dc0ea5defc38baab(全部元素都是String的Collection)等。</p><p>清单11:使用要被遍历的对象中的元素的上级类型的循环变量<br> String[] strings = {"A", "B", "C", "D"};<br> Collection10561f52a538bad7dc0ea5defc38baab list = java.util.Arrays.asList(strings);<br> for (Object str : list) {<br>     System.out.println(str);/* 依次输出“A”、“B”、“C”、“D” */<br> }</p><p>循环变量的类型可以和要被遍历的对象中的元素的类型之间存在能自动转换的关系。J2SE 1.5中包含了“Autoboxing/Auto-Unboxing”的机制,允许编译器在必要的时候,自动在基本类型和它们的包裹类(Wrapper Classes)之间进行转换。因此,用Integer型的循环变量来遍历一个int[]型的数组,或者用byte型的循环变量来遍历一个Collection9a55b736d1e9b58d26b48dae6facfa31,也是可行的。</p><p>清单12:使用能和要被遍历的对象中的元素的类型自动转换的类型的循环变量<br> int[] integers = {1, 2, 3, 4};<br> for (Integer i : integers) {<br>     System.out.println(i); /* 依次输出“1”、“2”、“3”、“4” */<br> }</p><p>注意,这里说的“元素的类型”,是由要被遍历的对象的决定的――如果它是一个Object[]型的数组,那么元素的类型就是Object,即使里面装的都是String对象也是如此。</p><p>可以限定元素类型的Collection</p><p>截至到J2SE 1.4为止,始终无法在Java程序里限定Collection中所能保存的对象的类型――它们全部被看成是最一般的Object对象。一直到J2SE 1.5中,引入了“泛型(Generics)”机制之后,这个问题才得到了解决。现在可以用Collectionb32f285eaba7a6752dff0bc229700674来表示全部元素类型都是T的Collection。</p><p>更多Java for循环的几种用法分析相关文章请关注PHP中文网!</p>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn