If you like, deduct 1 support in the comment area
List collection overview
- Ordered collection (sequence), users can precisely control the insertion position of each element in the list.
- Users can index anti-question elements by integer index and search for elements in the list
- Unlike the Set collection, the stored elements can be repeated
- Orderly and repeatable
List collection-specific methods (inherit all methods of the parent class Collection)
Method name | Description |
---|---|
void add(int index,E element) | Insert the specified element at the specified position in this collection |
E remove(int index) | Delete the element at the specified index and return the deleted element |
E set(int index,E element) | Modify the element at the specified index and return the modified element |
E get(int index) | Returns the element at the specified index |
Three kinds of traversal of List collection
- Method 1: Iterator: a unique traversal method for collections
- Method 2: ordinary for; traversal with index
- Method 3: Enhanced for (foreach) (another form of Iterator); the most convenient way of traversal The relationship between the two can be seen
through concurrent modification of exceptions
import java.util.*;
public class Dmeo {
public static void main(String[] args) {
//创建集合对象
List<String> list = new ArrayList<String>();
//添加元素
list.add("hello");
list.add("world");
//方法一:迭代器:集合特有的遍历方式
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
System.out.println(s);
}
System.out.println("---------------");
//方法二:普通for;带有索引的遍历方式
for(int i=0; i<list.size();i++) {
String s = list.get(i);
System.out.println(s);
}
System.out.println("---------------");
//方法三:增强for;最方便的遍历方式
for(String s : list) {
System.out.println(s);
}
}
}