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