J2SE5.0 New Features of Foreach

xiaoxiao2021-03-06  52

J2SE5.0 New Features of Foreach

晁 晁 攀 Smallnest@163.com

Foreach is available in C #:

Foreach (String Item IN f) {console.writeline (item);

Java also added such features:

Package com.kuaff.jdk5; import java.util. *; import java.util.collection; public class foreach {private collection c = null; private string [] belle = new string [4]; public foreach () {Belle [0] = "Xi Shi"; belle [1] = "Wang Zhaojun"; Belle [2] = "貂 禅"; belle [3] = "Yang Gui"; c = arrays.aslist (belle); Public void testcollection () {for (String B: c) {system.out.println ("Once weathered:" b);}} public void testArray ()}} public void testArray ()} .println ("Once the Name:" b);}}} public static void main (string [] args) {foreach Each = new foreach (); Each.TestCollection (); Each.TestArray ();}}

For collection types and array types, we can access it through Foreach syntax. In the above example, we have to access arrays in turn, it is troubles:

For (int i = 0; i

Now just need the following simple statement:

For (String B: belle) {system.out.println ("Once you've ate:" b);

More visiting the collection is more obvious. I used to access the collection code:

ITERATOR IT = C.ITerator (); it.hasnext ();) {string name = (string) it.next (); system.out.println ("Once Week:" Name);

Now we only need the following statement:

For (String B: C) {System.out.println ("Once Week:" B);

Foreach is not universal, it also has the following shortcomings:

In the previous code, we can perform the REMOVE operation via the Iterator. Iterator it = c.iterator (); it.hasnext ();)

{

iTremove ()

}

However, in the current Foreach version, we cannot delete the objects contained in the collection. You can't replace objects.

At the same time, you cannot parallel with more than multi-collection. So, when we write the code, you have to use it.

转载请注明原文地址:https://www.9cbs.com/read-83311.html

New Post(0)