Home > Java > JavaBase > body text

Three traversal methods of java collection ArrayList

王林
Release: 2019-11-30 15:56:54
forward
3201 people have browsed it

Three traversal methods of java collection ArrayList

ArrayList

ArrayList uses continuous memory units to store data elements and is a dynamic array whose capacity can grow dynamically.

When a data element is added or removed (except for the last position), ArrayList needs to move all elements behind the added (or removed) element. So inserting and deleting elements is slower, and querying is faster.

At the same time, the ArrayList thread is unsafe! Generally, ArrayList is used in single threads, while Vector and CopyOnWriteArrayList are generally used in multi-threads.

Recommended java related video tutorials: java online learning

Note:

1, ArrayList has been covered tostring can print the results directly.

2. toArray() will convert elements into Object type.

ArrayList traversal methods

ArrayList has three traversal methods, namely:

1. Iterator traversal

Iterator<Integer> it = arrayList.iterator();
while(it.hasNext()){
    System.out.print(it.next() + " ");
}
Copy after login

2. Index value traversal

for(int i = 0; i < arrayList.size(); i++){
   System.out.print(arrayList.get(i) + " ");
}
Copy after login

3. for loop traversal

for(Integer number : arrayList){
   System.out.print(number + " ");
}
Copy after login

Note: It should be noted that when traversing ArrayList, traversal through index values ​​is the most efficient, followed by for loop traversal, and iterator traversal is the lowest.

More related articles and tutorials are recommended: Java language introduction

The above is the detailed content of Three traversal methods of java collection ArrayList. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!