Traversal of the 1.Collection collection
The collection collection is not directly traversed, so we have to be able to traverse it indirectly, we know the array is easy to implement the variable, we can do this:
Use object[] ToArray (): Converts a set into an array, enabling the collection to traverse
Code implementation:
1 Packagecn.itcast_01;2 3 Importjava.util.ArrayList;4 Importjava.util.Collection;5 6 /*7 * Traversal of the collection. It is actually getting each element in the collection in turn. 8 * 9 * object[] ToArray (): Sets the set to the array, you can implement the collection of traversalTen */ One Public classCollectionDemo3 { A Public Static voidMain (string[] args) { - //To create a collection object -Collection C =NewArrayList (); the - //adding elements -C.add ("Hello");//Object obj = "Hello"; -C.add ("World"); +C.add ("Java"); - + //Traverse A //object[] ToArray (): Sets the set to the array, you can implement the collection of traversal atobject[] Objs =C.toarray (); - for(intx = 0; x < objs.length; X + +) { - //System.out.println (objs[x]); - //I know that the element is a string, and I want to know the length of the element while I get the element. - //System.out.println (objs[x] + "---" + objs[x].length ()); - //the above implementation is not possible, becausethere is no length () method in Object in //If we want to use the string method, we must restore the element to a string - //Down Transformation toString s =(String) objs[x]; +SYSTEM.OUT.PRINTLN (S + "---" +s.length ()); - } the } *}
The results are as follows:
Java Basic Knowledge Hardening Collection Framework note 05:collection Collection traversal