Collection Frame (collection traversal collection to array traversal)

Source: Internet
Author: User

Collection interface member Methods

Object[] ToArray ()
The collection can be traversed by transferring the set to the array.

Iterator Iterator ()
Iterators, private traversal of collections

 package cn.itcast_01;import java.util.arraylist;import java.util.collection;/* * Traversal of the   collection. It is actually getting each element in the collection in turn.  *  * object[] toarray (): Sets the set to the array, can implement the collection traversal  */public class  Collectiondemo3 { public static void main (String[] args)  {  //   Create Collection Object   collection c = new arraylist ();  //  add element    c.add ("Hello"); // object obj =  "Hello";  upward transformation   c.add ("World");   c.add ("Java");  //  Traversal   // object[] toarray (): Sets the set to the array, you can implement the collection of traversal   object[] objs = c.toarray ();  for  (int x = 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] +  "---" &Nbsp;+ objs[x].length ()); This code should be an error, why? Because Objs[x] is an element, and each of these elements is of type object, and the object type has no Length () method    //This paragraph why System.out.println (Objs[x] , because the ToString () method of it (Objs[x]) is called by default, and objs[x] +  "---"  + objs[x].length () needs to invoke the unique features of the string                   //  The above implementation is not possible because there is no length () method in object    //  if we want to use a string method, we must restore the element to a string    //  Down Transformation    String s =  (String)  objs[x];   system.out.println (s  +  "---"  + s.length ());   } }}

This article from "GD" blog, reproduced please contact the author!

Collection Frame (collection traversal collection to array traversal)

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.