This article is a mirror article of machine translation, please click here to jump to the original article.

View: 14824|Reply: 0

[Communication] java:list和set集合的遍历

[Copy link]
Posted on 1/4/2015 1:30:48 PM | | |

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);
  }






Previous:Traversal of List collection in java and comparative analysis of two implementation classes
Next:He is a senior brother, he is a loli girl, why did he give her a cup?
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com