ImportJava.util.*;classperson{PrivateString name; Private intAge ; Person (String name,intAge ) { This. Name =name; This. Age =Age ; } PublicString GetName () {returnname; } Public intGetage () {returnAge ; }}classDemo { Public Static voidMain (string[] args) {ArrayList Al=NewArrayList (); Al.add (NewPerson ("lisi01", 30)); Al.add (NewPerson ("lisi02", 32)); Al.add (NewPerson ("lisi03", 33)); Al.add (NewPerson ("lisi04", 35)); Iterator it=Al.iterator (); while(It.hasnext ()) {System.out.println (It.next (). GetName ()); } } }
Using It.next (). GetName () can cause problems,
The reason is that the "lisi01", 30 in ArrayList, will be promoted to Object,it.next () returns an object of type objects, there is no GetName method in object,
The cast should be cast:
while (It.hasnext ()) { = (person) it.next (); System.out.println (It.next (). GetName ());}
Problems caused by the promotion of classes in Java