-4

I've seen a different approach of using the FOR loop like this after create a "List" object type.

List<Focus> focuses = new ArrayList<Focus>();
String my_string = "";
for (Focus obj1 : list_obj_x) {
    my_string += obj1;
}

I don't understand how this FOR loop works in this situation.

Thanks

4

3 に答える 3

3

It's called enhanced for-loop/For-Each construct. introduced in java 1.5. it was introduced primarly to iterate over collections and arrays.

This:

List<Focus> focuses = new ArrayList<Focus>();
String my_string = "";
for (Focus obj1 : list_obj_x) {
    my_string += obj1;
}

is same as

List<Focus> focuses = new ArrayList<Focus>();
String my_string = "";
for (int i=0; i<focuses.size(); i++) {
    my_string += focuses.get(i);
}

Note that however, you can only use for-each loop for those objects which implement Iterable interface.

Implementing this interface allows an object to be the target of the "foreach" statement.

于 2013-02-15T16:28:03.083 に答える
1

Iterable<X>拡張されたforループは、配列を実装する任意のオブジェクトで使用できます。これは、イテレータでforループを使用するのと同じです(イテレータの場合)。

// with Iterables:

Iterable<String> iterableStrings = getListOfStrings();

// standard for loop
for (Iterator<String> it = iterableStrings.iterator(); it.hasNext(); ) {
   String s = it.next();
   System.out.println(s);
}

// enhanced for loop
for (String s : iterableStrings) {
   System.out.println(s);
}

// with arrays:

String[] stringArray = getStringArray();

// standard for loop
for (int i = 0; i < stringArray.length; i++) {
   String s = stringArray[i];
   System.out.println(s);
}

// enhanced for loop
for (String s : stringArray) {
   System.out.println(s);
}

使用法は、リストや配列などの「インデックス付きコレクション」に限定されません。

参照

JLS 14.14.2

于 2013-02-15T16:42:25.950 に答える
1
for (Focus obj1 : list_obj_x) {
    my_string += obj1;
}

When you see the colon (:) read it as “in.” The loop above reads as “for each Focus obj1 in list_obj_x.” As you can see, the for-each construct combines beautifully with generics. It preserves all of the type safety, while removing the remaining clutter. Because you don't have to declare the iterator, you don't have to provide a generic declaration for it. (The compiler does this for you behind your back, but you need not concern yourself with it.)

And equivalent to above for each loop is:

for (int i =0 ; i< list_obj_x.size(); i++) {
    my_string += list_obj_x.get(i);
}
于 2013-02-15T16:28:14.883 に答える