Original URL: http://blog.csdn.net/player26/article/details/3955906
- Import java.util.ArrayList;
- Import Java.util.Iterator;
- Import java.util.List;
- Public class Listtest {
- public static void Main (string[] args) {
- list<integer> list = new arraylist<integer> ();
- List.add (1);
- List.add (2);
- List.add (3);
- For (Iterator i = List.iterator (); I.hasnext ();)
- System. out.println (I.next ()); //Line 1
- }
- }
- Public class ListTest2 {
- public static void Main (string[] args) {
- List List = new ArrayList ();
- List.add (new Integer (100));
- List.add (new Float (150.60));
- List.add (new String ("abc"));
- For (Iterator i = List.iterator (); I.hasnext ();)
- System. out.println (I.next ());
- list<integer> list = new arraylist<integer> ();
- List.add (1);
- List.add (2);
- List.add (3);
- for (Integer i:list) {
- System.out.println (i); Ok
- // }
- }
- }
- Although the list's generic is an integer, the type returned by. Next () is an object
- Public class ListTest3 {
- public static void Main (string[] args) {
- //list<integer> List = new arraylist<integer> ();
- //List.add (1);
- //List.add (2);
- //List.add (3);
- //for (Iterator i = List.iterator (); I.hasnext ();) {
- //Integer integerref = (integer) i.next ();//line 1
- ////compile Error
- //System.out.println (INTEGERREF);//Line 2
- // }
- list<integer> list = new arraylist<integer> ();
- List.add (1);
- List.add (2);
- List.add (3);
- For (iterator<integer> i = List.iterator (); I.hasnext ();) {
- Integer integerref = I.next (); //Line 1
- //OK
- System. out.println (INTEGERREF); //Line 2
- }
- }
- }
There are three ways to traverse the list
list<a> list = new arraylist<a> ();
List.add (New A ());
List.add (New A ());
...
The first type:
for (iterator<a> it = List.iterator (); It.hasnext (); ) {
....
}
This way in the loop
Data locking during execution, performance is slightly poor, at the same time, if you want to remove an element during the loop, you can only call the It.remove method, you cannot use the List.remove method, or you must have a concurrent access error.
The second type:
for (A a:list) {
.....
}
Internal call the first, in the bottle, this loop way there are other restrictions, do not recommend the use of it
The third type:
for (int i=0; I<list.size (); i++) {
A = List.get (i);
...
}
Internal non-locking, the most efficient, but when writing multi-threading to consider the problem of concurrent operation!
Traversal of list in "Go" Java