|
There are three ways to traverse a 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 is in a cycle At the same time, if you want to remove an element in the process of pleasure, you can only call the it.remove method, you cannot use the list.remove method, otherwise there will be an error of concurrent access. But the compatibility is the best, suitable for the Collection collection
The second type: for(A a : list) { ..... } The for each method is still an iterator, the first one is called internally, and the soup is not changed, and there are other limitations to this circular method, so it is not recommended to use it It can only be used above JK1.5 with poor compatibility Set is best to use this one
The third type: for(int i=0; i<list.size(); i++) { A a = list.get(i); ... } for loop, traversing the contents of a List collection only works for List, because List is an ordered collection , the internal is not locked, the highest efficiency, but when writing multithreading, the problem of concurrent operations should be considered! Traversing a Set collection is the same way as a List, but you can't use a for loop to iterate through a Set collection because there's no get() method in the Set collection. But it can be looped with enhancements Traverse the Set collection Set<String> set = new HashSet<String>(); set.add("qqq"); set.add("www"); set.add("eee"); set.add("rrr");
for(String s : set){ System.out.println("set="+s); }
|