Java Basic Knowledge Hardening Collection Framework note 05:collection Collection traversal

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.