Home>Article>Java> Three traversal methods of java collection ArrayList

Three traversal methods of java collection ArrayList

王林
王林 forward
2019-11-30 15:56:54 3136browse

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, whileVectorandCopyOnWriteArrayListare 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 it = arrayList.iterator(); while(it.hasNext()){ System.out.print(it.next() + " "); }

2. Index value traversal

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

3. for loop traversal

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

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete