Three simple ways to traverse a collection to get its objects , summarized here
Method 1: Turn the collection into an array, and then iterate through the array
Object[] obj = list.toArray(); for(Object s: obj){ System.out.println((String) s); }Method 2: Get() method. But it can only be used in list collections, only List collections have index values.
for(int i = 0;i<list.size();i++){ System.out.println(list.get(i)); }Method 3: 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("Junior"); collection.add("Zhang San"); collection.add("Li Si"); collection.add("Wang Wu"); //1. Convert collection into array Object[] Object[] objectsArrC = collection.toArray(); for (Object object : objectsArrC) { String string = (String) object; // cast object to string output System.out.println(string); } //2.get() method gets element for (int i = 0;i < collection.size();i++){ //get() can only be used in list collections, so the conversion form needs to be converted here. System.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("First Junior"); list.add("Zhang San"); list.add("Li Si"); list.add("Wang Wu"); //1. Convert the collection into an array Object[] Object[] objectsArrL = list.toArray(); for (Object object : objectsArrL) { String string = (String) object; //Capt the object into a string and output System.out.println(string); } //2. Through the 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()); } }} The above is all the content of this article. I hope that the content of this article will be of some help to everyone’s study or work. I also hope to support Wulin.com more!