1 PackageBasic;2 3 Importjava.util.ArrayList;4 ImportJava.util.Iterator;5 Importjava.util.List;6 7 //list how to use8 Public classListdemo {9 Ten Public Static voidMain (string[] args) { One //instantiating a list Alist<string> lists =NewArraylist<string>(); - - //adding elements theLists.add ("a"); -Lists.add ("B"); -Lists.add ("C"); -Lists.add ("D"); + dataprintbyit (lists); -Lists.add (3, "E"); + dataprintbyit (lists); A at //modifying elements -Lists.set (4, "F"); - dataprintbyit (lists); - - //Delete Element (index or object) -Lists.remove (0); inLists.remove ("B"); - Dataprintbyforeach (lists); to + //Enquiry -String item = lists.get (1); the intn = Lists.indexof ("F"); *System.out.print ("Get:" + Item + "INDEXOF:" +n); $ Panax Notoginseng //History (original method and new feature) - dataprintbyit (lists); the Dataprintbyforeach (lists); + A //Clear the //lists.clear (); + - } $ $ //Traverse list-Primitive Method - Public Static voidDataprintbyit (list<string>lists) { -Iterator<string> it =lists.iterator (); the while(It.hasnext ()) { -System.out.print (It.next () + "");Wuyi } the System.out.println (); - } Wu - //Traverse List-foreach method, Java8 new feature About Public Static voidDataprintbyforeach (list<string>lists) { $ Lists.foreach ( -(x)-System.out.print (x + "") - ); - System.out.println (); A } + the //traversing the List-foreach method - Public Static voidDataprintbyfe (list<string>lists) { $ for(String item:lists) { the System.out.println (item); the } the System.out.println (); the } - in}
How to use the list in Java