List集合特点:有序、可重复 ;ArrayList 底层的数据结构是顺序存储;LinkedList 底层的数据结构是链式存储;
(1)基本方法。
用于查询的基本方法是对Collection元素的增加和删除,包括:
int size():返回集合元素的个数。
boolean isEmpty():如果Collection不包含元素,则返回true。
boolean Contains(Objecto):如果Collection 包含指定的元素,则返回true。
boolean add(E e):向集合中增加一个元素,成功返回true,否则返回false。
boolean remove(Object o):从Collection中移除指定元素的单个实例。
(2)批量操作方法。
批量操作方法是将整个集合作为一个单元来操作;包括:
boolean addAll(Collection c):将指定 collection中的所有元素都添加到当前Collection,成功返回true。
boolean removeAll(Collection c):删除所有元素,成功返回true。
boolean containsAll(Collection c):如果 Collection包含指定Collection中的所有元素,则返回true。
boolean retainAll(Collection c):保留 Collection中那些也包含在指定Collection中的元素。
void clear():移除Collection中的所有元素。
(3)数组操作方法。
把集合转换成数组的操作,包括:
Obiect[] toArray():返回包含Collection中所有元素的数组。
<T> T[] toArray(T[]a):返回包含Collection中所有元素的数组。返回数组的类型与指定数组的运行时类型相同。
(4)迭代操作方法。
迭代操作是为集合提供顺序获取元素的方法。Iterator iterator()返回一个实现迭代接口的对象。
迭代接口定义的方法有boolean hasNext()。只要集合存在下一个元素,可用Object next()方法获取下一个元素。
import java.util.*;
//集合的遍历,迭代器的使用
public class Test{
public static void main(String[] args){
Collection<String> myList =new ArrayList<>(); //定义一个存有字符串的集合
String[] strs={"工藤新一","怪盗基德","鲁邦三世","宫野明美","琴酒","伏特加","天等指天椒"};
Collections.addAll(myList, strs); //将数组中的内容复制到集合里面去
System.out.println("迭代之前:"+myList); //输出集合中的内容
Iterator<String> myItertor =myList.iterator(); //定义集合的迭代器
while(myItertor.hasNext()){
//通过迭代器获取元素
String element = myItertor.next();
//可以进行遍历输出
System.out.println(element);
//可以通过迭代器对集合进行操作
if (element.length()>4){
System.out.println("“"+element+"”字符长度大于4,删除!");
myItertor.remove();
}
}
System.out.println("迭代之后:"+myList); //输出集合中的内容
}
}
运行结果:
2.增强for遍历
import java.util.*;
//增强for遍历集合
public class Test{
public static void main(String[] args){
Collection<String> myList =new ArrayList<>(); //定义一个存有字符串的集合
String[] strs={"工藤新一","怪盗基德","鲁邦三世","宫野明美","琴酒","伏特加","天等指天椒"};
Collections.addAll(myList, strs); //将数组中的内容复制到集合里面去
System.out.println("=================增强for遍历====================");
//采用 for遍历
for (String s : myList) {
System.out.println(s);
}
}
}
运行结果;