Java iterator listiteator

Source: Internet
Author: User
Import Java. util. *; class animal {string name; int age;} public class list {public static void main (string ARGs []) {arraylist list = new arraylist (); list. add (1); list. add (2); list. add (3); list. add (4); list. add (5); list. add (6); // use iterator to traverse arraylist // list. remove (object) 3); For (iterator it = List. iterator (); it. hasnext ();) {system. out. println (it. next ();} * directly use listiterator to traverse the arraylist; * For (listiterator it = List. listiterator (); it. hasnext ();) {system. out. println (it. next ();} * // use iterator to delete data * For (iterator it = List. iterator (); it. hasnext ();) {If (it. next () = (object) 4) {It. remove () ;}for (iterator it2 = List. iterator (); it2.hasnext ();) {system. out. println (it2.next ();} Use listiterator to add the element for (listiterator it = List. listiterator (); it. hasnext ();) {If (it. next () = (object) 3) {It. add ("three") ;}}for (listiterator it2 = List. listiterator (); it2.hasnext ();) {system. out. println (it2.next ();} For (listiterator it = List. listiterator (); it. hasnext ();) {It. add ("add"); it. next () ;}for (iterator it2 = List. iterator (); it2.hasnext ();) {system. out. println (it2.next ();} * // system. out. println (list. descendingiterator () ;}}/** note: During the iteration process, container operations cannot be added. modify. delete operation. this will cause concurrent operation exceptions, because the elements cannot be changed by means other than the iterator during the iterator iteration process, therefore, you can only use the method in the iterator to modify the container. Therefore, the following operation may encounter an error * For (iterator it = List. iterator (); it. hasnext ();) * {* If (it. next (). equals ("ABC") * List. add ("def"); // This will show *} * use listiterator to add the element * For (listiterator it = List. listiterator (); it. hasnext ();) * {* If (it. add ("google") // you may have added *} ***** 7:57:39 **/

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.