Collection-to-array traversal in Java

Source: Internet
Author: User

A method of iterating a collection in Java when a collection goes to an array traversal, which is also called collection in ToArray ().

Code:

public static void Main (string[] args) {
TODO auto-generated Method Stub
Collection c=new ArrayList ();
C.add (New Student ("KJ", 12));
C.add (New Student ("Uj", 13));
C.add (New Student ("TJ", 15));
C.add (New Student ("CJ", 14));

object[]ob= C.toarray ();//Convert collection to an array

for (int i=0;i<ob.length;i++) {
Student s= (Student) ob[i];
System.out.println (S.getname () + "..." +s.getage ());
}

}

Operation Result:

Kj... 12
Uj ... 13
Tj... 15
Cj... 14

It is important to note that the ToArray () method is called when the collection-to-array is traversed, and an array object of the object class needs to be declared. When the type of the collection is an object, it is not possible to get the object arguments directly by invoking the object class's method, because even if the student object is stored, the near Ascension becomes object. The disadvantage of polymorphism is that you cannot use the properties and methods of subclasses. If you want to use the properties and methods of the subclass, you need to turn the oject array of OB, that is, the type is strong. Student s= (Student) ob[i]. The advantage of this is that I can iterate through all the elements of the student and manipulate it.

Collection-to-array traversal in Java

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.