What is Iterable?

In the exercise "Draw hollow Polygon on Map, using addHole() method", object of ArrayList<LatLng> is passed to addHole() as Iterable<latlng>. And...what is Iterable?

Described in Android document: Iterable<T>: Instances of classes that implement this interface can be used with the enhanced for loop. In Java 6 document (Android now support JDK6), this interface allows an object to be the target of the "foreach" statement.

Here is example to use Iterable in for loop and while loop.

example to use Iterable in for loop and while loop


package com.example.androiditerable;

import java.util.ArrayList;
import java.util.Iterator;

import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

TextView text_for = (TextView)findViewById(R.id.result1);
TextView text_while = (TextView)findViewById(R.id.result2);

ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("Sunday");
arrayList.add("Monday");
arrayList.add("Tuesday");
arrayList.add("Wednesday");
arrayList.add("Thursday");
arrayList.add("Friday");
arrayList.add("Saturday");

String result_for = "";
for(String item : arrayList){
result_for += item + "\n";
}
text_for.setText(result_for);

Iterator<String> iterator = arrayList.iterator();
String result_while = "";
while (iterator.hasNext()){
result_while += iterator.next() + "\n";
}
text_while.setText(result_while);

}

}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<TextView
android:id="@+id/result1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/result2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>


0 Response to "What is Iterable?"

Post a Comment