For iterating through the collection to get its object , here's a summary of the three simple ways
Mode one: Make the collection into an array and iterate through the array
object[] obj = List.toarray ();
for (Object s:obj) {
System.out.println ((String) s);
}
Way two: Get () method gets. But only used in the list collection, only the list collection has index values.
for (int i = 0;i<list.size (); i++) {
System.out.println (List.get (i));
}
Mode three: through the iterator
Listiterator it = List.listiterator ();
while (It.hasnext ()) {
System.out.println (It.next ());
}
There are two cases to compare
Collection Case:
Import java.util.ArrayList;
Import java.util.Collection;
Import Java.util.Iterator;
Import java.util.List;
public class Pasework {public static void main (string[] args) {collectiontest ();
public static void Collectiontest () {Collection <string>collection = new arraylist<string> ();
Collection.add ("the Junior");
Collection.add ("small Two");
Collection.add ("John");
Collection.add ("Dick");
Collection.add ("Harry");
1. Set to array object[] object[] OBJECTSARRC = Collection.toarray (); For (object OBJECT:OBJECTSARRC) {string string = (String) object;//cast object to string output System.out.println (Strin
g); The//2.get () method gets the element for (int i = 0;i < Collection.size (); i++) {//get () can only be used in the list collection, so you need to convert the form here Syst
Em.out.println (((arraylist<string>) collection). Get (i));
//3. iterator iterator<string> it = Collection.iterator ();
while (It.hasnext ()) {System.out.println (It.next ()); }
}
}
List Case:
Import java.util.ArrayList;
Import java.util.Collection;
Import java.util.List;
Import Java.util.ListIterator;
public class Pasework {public
static void Main (string[] args) {
listtest ();
}
public static void Listtest () {
list<string> List = new arraylist<string> ();
List.add ("the Junior");
List.add ("small Two");
List.add ("John");
List.add ("Dick");
List.add ("Harry");
1. Set to array object[]
object[] objectsarrl = List.toarray ();
For (object object:objectsarrl) {
string = (String) object;//cast object to string output
System.out.println (string );
}
2. Through get () method for
(int i = 0; i < list.size (); i++) {
System.out.println (List.get (i));
}
3. Iterator
listiterator<string> iterator = List.listiterator ();
while (Iterator.hasnext ()) {
System.out.println (Iterator.next ());
}
}}
Above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, but also hope that a lot of support cloud Habitat community!