容器(Collection),也称之为集合,用来容纳和管理数据。
1. 单例集合 1.1 概念单例集合:将数据一个一个的进行存储。
Collection接口:是单例集合根接口,有两个子接口,分为List接口(存储有序,可重复,“动态”数组),Set接口(存储无序,不可重复,数学中的“集合”)
List接口:ArrayList类,linkedList类,Vector类
Set接口:linkedHashSet类,HashSet类,TreeSet类
1.2 Collection接口中的抽象方法| 方法 | 说明 |
|---|---|
| boolean add(Object element) | 增加元素到容器中 |
| boolean remove(Object element) | 从容器中移除元素 |
| boolean contains(Object element) | 容器中是否包含该元素 |
| int size() | 容器中元素的数量 |
| boolean isEmpty() | 容器是否为空 |
| void clear() | 清空容器中所有元素 |
| Iterator iterator() | 获得迭代器,用于遍历所有元素 |
| boolean containsAll(Collection c) | 本容器是否包含c容器中的所有元素 |
| boolean addAll(Collection c) | 将容器c中所有元素增加到本容器 |
| boolean removeAll(Collection c) | 移除本容器和容器c中都包含的元素 |
| boolean retainAll(Collection c) | 取本容器和容器c中都包含的元素,移除非交集元素 |
| Object[] toArray() | 转化成Object数组 |
特点:
- 有序:元素存入集合的顺序和取出的顺序一致,List中每个元素都有索引标记,可以根据元素的索引标记访问元素,从而精确控制这些元素
- 可重复:List允许加入重复的元素。更确切地讲,List通常允许满足e1.equals(e2)的元素重复加入容器。
常用方法:
除了Collection接口中的方法,List多了一些跟顺序(索引)有关的方法
| 方法 | 说明 |
|---|---|
| void add(int index,Object element) | 在指定位置插入元素,以前元素全部后移一位 |
| Object set(int index,Object element) | 修改指定位置的元素 |
| Object get(int index) | 返回指定位置的元素 |
| Object remove(int index) | 删除指定位置的元素,后面元素全部前移一位 |
| int indexOf(Object o) | 返回第一个匹配元素的索引,如果没有该元素,返回-1 |
| int lastIndexOf(Object o) | 返回最后一个匹配元素的索引,如果没有该元素,返回-1 |
ArrayList是List接口的实现类,是List存储特征的具体实现
ArrayList底层是用数组实现的存储。
**特点:**查询效率高,增删效率低,线程不安全
基本实现:
import java.util.ArrayList;
import java.util.List;
public class ArrayListTest {
public static void main(String[] args) {
List list = new ArrayList<>(); //实例化ArrayList容器
list.add("abab"); //添加元素
list.add("cdcd");
list.add("efef");
list.add(1,"小二"); //指定位置不能大于元素个数
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i)); //获取元素
}
System.out.println("list元素的个数:"+list.size()); //元素个数
//删除元素
String value = list.remove(1); //根据索引位置删除元素,返回被删除的元素
System.out.println(value);
boolean flag = list.remove("haha"); //删除指定元素,成功返回true,未找到指定元素返回false
System.out.println(flag);
String value2 = list.set(1, "haha");//替换元素,返回被替换掉的元素
System.out.println(value2);
System.out.println("list容器是否包含abab元素:"+list.contains("abab")); //判断容器是否包含该元素,是则返回true,否则返回false
System.out.println(list.indexOf("haha")); //indexOf方法返回的是元素在容器中第一次出现的位置,如果不存在返回-1
System.out.println(list.lastIndexOf("haha")); //lastIndexOf方法返回的是元素在容器中最后一次出现的位置,如果不存在返回-1
Object[] arr = list.toArray(); //将ArrayList转换为Object数组,不能将转换的数组做强制类型转换
for (int i = 0; i < arr.length; i++) {
String str = (String) arr[i];
System.out.println(str);
}
String[] arr2 = list.toArray(new String[list.size()]); //将单例集合转换为指定类型的数组
for (int i = 0; i < arr2.length; i++) { //可以将单例集合转换成指定类型数组,但类型需要参考泛型中的类型
System.out.println(arr2[i]);
}
list.clear(); //清空容器
System.out.println("容器的个数:"+list.size()); //0
System.out.println("容器是否为空:"+list.isEmpty()); //判断容器是否为空,为空返回true,非空返回false
List a = new ArrayList<>();
a.add("a");
a.add("b");
a.add("c");
List b = new ArrayList<>();
b.add("c");
b.add("d");
b.add("e");
System.out.println(a.addAll(b)); //容器的并集操作,a并b
for (String str: a) {
System.out.println(str); //a b c c d e
}
List a1 = new ArrayList<>();
a1.add("a");
a1.add("b");
a1.add("c");
List b1 = new ArrayList<>();
b1.add("c");
b1.add("d");
b1.add("e");
System.out.println(a1.retainAll(b1)); //容器的交集操作,a交b
for (String str: a1) {
System.out.println(str); //c
}
List a2 = new ArrayList<>();
a2.add("a");
a2.add("b");
a2.add("c");
List b2 = new ArrayList<>();
b2.add("c");
b2.add("d");
b2.add("e");
System.out.println(a2.retainAll(b2)); //容器的差集操作,a-b
for (String str: a2) {
System.out.println(str); //a b
}
}
}
1.3.2 Vector容器类
Vector底层使用数组实现的,相关的方法都加了同步检查,因此**“线程安全,效率低”**。比如,indexOf方法增加了synchronized同步标记。
Vector的使用与ArrayList是相同的,因为他们都是实现了List接口,对List接口中的抽象方法做了具体实现。
Vector与ArrayList的区别在于Vector多线程安全,而ArrayList多线程不安全。
简单实现:
public class VectorTest {
public static void main(String[] args) {
List v = new Vector<>();
v.add("aaa"); //增加元素
v.add("bbb");
v.add("ccc");
for (int i = 0; i < v.size(); i++) {
System.out.println(v.get(i)); //获取元素
}
}
}
Stack容器:
Stack栈容器是Vector的一个子类,实现了一个标准的后进先出(LIFO)的栈。
特点:后进先出,通过5个操作方法对Vector进行扩展,允许将向量视为堆栈。
简单实现:
public class StackTest {
public static void main(String[] args) {
Stack stack = new Stack<>();
stack.push("aaa"); //元素压栈
stack.push("bbb");
stack.push("ccc");
System.out.println(stack.size()); //stack中元素的个数
System.out.println(stack.pop()); //元素弹栈
System.out.println(stack.empty()); //判断栈是否为空,是则返回true,否则返回false
System.out.println(stack.peek()); //查看栈顶元素
System.out.println(stack.search("aaa")); //返回元素在栈容器中的位置,栈元素位置从1开始,从栈顶开始
}
}
括号匹配问题:
public class StackTest02 {
public void symmetry(){
String str = "{...[..(..)..]...}.(..)..[..]..{..}";
Stack stack = new Stack<>();
boolean flag = true;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == '('){ //如果是左括号就压栈
stack.push(")");
}
if (ch == '['){
stack.push("]");
}
if (ch == '{'){
stack.push("}");
}
if (ch == ')'||ch == ']'||ch == '}'){ //是右括号就弹栈
if (stack.empty()){
flag = false;
break;
}
String topStr = stack.pop();
if (topStr.charAt(0) != ch){
flag = false;
break;
}
}
}
if (!stack.empty()){
flag = false;
}
if (flag){
System.out.println("匹配成功!");
}else {
System.out.println("匹配不成功!");
}
}
public static void main(String[] args) {
StackTest02 stack = new StackTest02();
stack.symmetry();
}
}
1.3.3 linkedList容器类
linkedList底层用双向链表实现的存储。
**特点:**查询效率低,增删效率高,线程不安全
linkedList的使用(List标准):
linkedList实现了List接口,使用linkedList是具备List的存储特征的(有序,元素可重复)。
Listlist = new linkedList<>(); list.add("aaa"); //添加元素 list.add("bbb"); list.add("ccc"); list.add("aaa"); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); //获取元素 }
linkedList的使用(非List标准):
public class linkedListTest02 {
public static void main(String[] args) {
linkedList linkedList = new linkedList<>();
linkedList.addFirst("aaa"); //将指定元素插入到开头
linkedList.addLast("bbb"); //将指定元素插入到结尾
linkedList.addFirst("ccc");
for (String str:linkedList) {
System.out.println(str); //ccc aaa bbb
}
System.out.println(linkedList.getFirst()); //返回此链表的第一个元素
System.out.println(linkedList.getLast()); //返回此链表的最后一个元素
linkedList.removeFirst(); //移除此链表中的第一个元素,并返回这个元素
linkedList.removeLast(); //移除此链表中的最后一个元素,并返回这个元素
linkedList.pop(); //从此链表所表示的堆栈处弹出一个元素,相当于removeFirst
linkedList.push("ddd"); //将元素推入此链表所表示的堆栈中,相当于addFirst(E e)
System.out.println(linkedList.isEmpty()); //判断此链表是否为空,是则返回true,否则返回false
}
}
1.4 Set接口
Set接口继承自Collection接口,Set接口中没有新增方法,方法和Collection保持完全一致。
特点:
- 无序:Set中的元素没有索引,只能遍历查找
- 不可重复:不允许加入重复的元素,新元素如果和Set中某个元素通过equals()方法对比为true,则只能保留一个。
Set常用的实现类有:HashSet、TreeSet等
1.4.1 HashSet容器类HashSet是采用哈希算法实现,底层实际是用HashMap实现的(HashSet本质就是一个简化版的HashMap),因此查询效率和增删效率都比较高。
基本实现:
public class HashSetTest {
public static void main(String[] args) {
Set set = new HashSet<>();
set.add("aaa"); //添加元素
set.add("bbb");
set.add("ccc");
set.add("aaa"); //不能有重复元素,所以此时Set容器中只有aaa bbb ccc,没有两个aaa
//获取元素,在Set容器中没有索引,所以没有对应的get(int index)方法
for (String str:set) { //可以通过foreach循环来获取元素
System.out.println(str);
}
System.out.println(set.remove("aaa")); //删除元素,成功返回true,失败返回false
System.out.println(set.size()); //返回元素的个数
}
}
HashSet存储特征分析:
HashSet是一个没有重复元素且不保证元素的顺序的集合,是线程不安全的。而且HashSet允许有null元素。
无序:在HashSet中底层是使用HashMap存储元素的。HashMap底层使用的是数组与链表实现元素的存储。元素在数组中存放时,并不是对有序存放的也不是随机存放的,而是对元素的哈希值进行运算决定元素在数组中的位置。
不重复:当两个元素的哈希值进行运算后得到相同的在数组中的位置时,会调用元素的equals()方法判断两个元素是否相同。如果元素相同则不会添加元素,如果不相同则会使用单向链表保存该元素。
通过HashSet存储自定义对象:
如果要想在自定义对象中实现不重复元素,需要在自定义对象中重写equals()方法和hashCode()方法。
Users对象:
public class Users {
private String username;
private int userage;
public Users(String username, int userage) {
this.username = username;
this.userage = userage;
}
public Users(){}
@Override
public String toString() {
return "Users{" +
"username='" + username + ''' +
", userage=" + userage +
'}';
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getUserage() {
return userage;
}
public void setUserage(int userage) {
this.userage = userage;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Users users = (Users) o;
return userage == users.userage && Objects.equals(username, users.username);
}
@Override
public int hashCode() {
return Objects.hash(username, userage);
}
}
测试类:
public class HashSetTest02 {
public static void main(String[] args) {
Set set = new HashSet<>();
Users u1 = new Users("xxx",18);
Users u2 = new Users("xxx",18);
set.add(u1);
set.add(u2);
System.out.println(u1.hashCode());
System.out.println(u2.hashCode());
for (Users user :
set) {
System.out.println(user);
}
}
}
1.4.2 TreeSet容器类
TreeSet是一个可以对元素进行排序的容器。底层实际是用TreeMap实现的,内部维持了一个简化版的TreeMap,通过key来存储Set的元素。TreeSet内部需要对存储的元素进行排序,因此需要给定排序规则。
排序规则实现方式:通过元素自身实现比较规则,通过比较器指定比较规则。
基本实现:
public class TreeSetTest {
public static void main(String[] args) {
Set set = new TreeSet<>();
set.add("aaa"); //添加元素
set.add("ddd");
set.add("bbb");
set.add("ccc");
set.add("aaa");
for (String str :
set) {
System.out.println(str); //遍历TreeSet容器,aaa bbb ccc ddd,在TreeSet内部对元素做了排序处理
}
}
}
通过元素自身实现比较规则:
需要实现Comparable接口中的compareTo方法,该方法中用来定义比较规则,TreeSet通过调用该方法来完成对元素的排序处理。
User类:
public class Users implements Comparable{ private String username; private int userage; public Users(String username, int userage) { this.username = username; this.userage = userage; } public Users(){} @Override public String toString() { return "Users{" + "username='" + username + ''' + ", userage=" + userage + '}'; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getUserage() { return userage; } public void setUserage(int userage) { this.userage = userage; } @Override public int compareTo(Users o) { //实现了compareTo方法,主要关键字是年龄,次要关键字是姓名(字典序) if (this.userage > o.getUserage()){ return 1; } if (this.userage == o.getUserage()){ return this.username.compareTo(o.getUsername()); } return -1; } }
实现类:
public class TreeSetTest02 {
public static void main(String[] args) {
Set set = new TreeSet<>();
Users u1 = new Users("xxx",18);
Users u2 = new Users("yyy",10);
Users u3 = new Users("aaa",10);
set.add(u1);
set.add(u2);
set.add(u3);
for (Users user :
set) {
System.out.println(user);
}
}
}
通过比较器实现比较规则:
需要单独创建一个比较器,比较器需要实现Comparator接口中的compare方法来定义比较规则。在实例化TreeSet时将比较器对象交给TreeSet来完成元素的排序处理,此时元素自身就不需要实现比较规则了。
创建比较器:
public class StudentComparator implements Comparator{ @Override public int compare(Students o1, Students o2) { //定义比较规则 if (o1.getAge() > o2.getAge()){ return 1; } if (o1.getAge() == o2.getAge()){ return o1.getName().compareTo(o2.getName()); } return -1; } }
Students类:
public class Students {
private String name;
private int age;
public Students(String name, int age) {
this.name = name;
this.age = age;
}
public Students(){}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Students students = (Students) o;
return age == students.age && Objects.equals(name, students.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "Students{" +
"name='" + name + ''' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
测试类:
public class TreeSetTest03 {
public static void main(String[] args) {
Set set = new TreeSet<>(new StudentComparator());
Students s1 = new Students("xxx",18);
Students s2 = new Students("yyy",20);
Students s3 = new Students("xyz",20);
set.add(s1);
set.add(s2);
set.add(s3);
for (Students stu :
set) {
System.out.println(stu);
}
}
}
1.5 单例集合使用案例
产生1-10之间的随机数[1,10]()闭区间,将不重复的10个随机数放到容器中。
List类型容器实现:
public class TestList {
public static void main(String[] args) {
List list = new ArrayList<>();
while (true){
int num = (int)(Math.random() * 10 + 1); //获取随机数
if (!list.contains(num)){ //判断随机数是否在list中已存在
list.add(num);
}
if (list.size() == 10){
break;
}
}
for (Integer i :
list) {
System.out.println(i);
}
}
}
Set类型容器实现:
public class TestSet {
public static void main(String[] args) {
Set set = new HashSet<>();
while (true){
int num = (int)(Math.random() * 10 + 1);
set.add(num); //由于Set类型容器不允许有重复元素的,所以不需要判断
if (set.size() == 10){
break;
}
}
for (Integer i :
set) {
System.out.println(i);
}
}
}
2. 双例集合
双例集合:基于Key与Value的结构存储数据。数学中的函数y=f(x)
Map接口:HashTable类,HashMap类,TreeMap类,linkedHashMap类,Properties类
2.1 Map接口介绍Map接口定义了双例集合的存储特征,它并不是Collection接口的子接口。双例集合的存储特征是以key与value结构为单位进行存储。
Map与Collection的区别:
- Collection中的容器,元素是孤立存在的,向集合中存储元素采用一个个元素的方式存储
- Map中的容器,元素都是成对存在的,每个元素由键与值两部分组成,通过键可以找对所对应的值。
- Collection中的容器称为单例集合,Map中的容器称为双例集合。
- Map中的集合不能包含重复的键,值可以重复,每个键只能对应一个值。
- Map中常用的容器为HashMap,TreeMap等。
Map的常用方法:
| 方法 | 说明 |
|---|---|
| V put(K key,V value) | 把key与value添加到Map集合中 |
| void putAll(Map m) | 从指定Map中将所有映射关系复制到此Map中 |
| V get(Object key) | 根据指定的key,获取对应的value |
| boolean containsKey(Object key) | 判断容器中是否包含指定的key |
| boolean containsValue(Object value) | 判断容器中是否包含指定的value |
| Set keySet() | 获取Map集合中所有的key,存储到Set集合中 |
| Set | 返回一个Set基于Map.Entry类型包含Map中所有映射 |
| void clear() | 删除Map中所有的映射 |
HashMap是Map接口的接口实现类,它采用哈希算法实现,是Map接口最常用的实现类。由于底层采用了哈希表存储数据,所以要求键不能重复,如果发生重复,新的值会替换旧的值。HashMap在查找、删除、修改方面都有非常高的效率。
基本操作:
public class TestHashMap {
public static void main(String[] args) {
Map map1 = new HashMap<>();
map1.put("a","A"); //添加元素
map1.put("b","B");
map1.put("c","C");
map1.put("d","D");
System.out.println(map1.get("a")); //获取元素
Set keys = map1.keySet(); //获取HashMap容器中所有元素,可以使用keySet方法与get方法一并完成
for (String key :
keys) {
String value = map1.get(key);
System.out.println(key + " --- " + value);
}
Set> entrySet = map1.entrySet(); //通过entrySet获取Map.Entry类型获取元素
for (Map.Entry entry :
entrySet) {
String key = entry.getKey(); //获取Key
String value = entry.getValue(); //获取Value
System.out.println(key + "---"+ value);
}
System.out.println("-------------------------");
Map map2 = new HashMap<>();
map2.put("f","F");
map2.put("c","CCC"); //因为map1和map2中有相同的key,被并过来的容器map1会将当前容器map2中key相同的value覆盖掉
map2.putAll(map1); //并集操作,将map1中所有元素并到map2中
Set keys2 = map2.keySet();
for (String key2 :
keys2) {
System.out.println(key2 + " --- " + map2.get(key2));
}
String value = map1.remove("b"); //删除元素,并把删除了的元素返回
System.out.println(value);
Set keys3 = map1.keySet();
for (String key3 :
keys3) {
System.out.println(key3 + " = " + map1.get(key3));
}
//判断key或者value是否存在,存在返回true,否则返回false
System.out.println(map1.containsKey("aaa")); //判断key,false
System.out.println(map1.containsKey("a")); //判断key,true
System.out.println(map1.containsValue("A")); //判断value,true
}
}
HashMap底层存储:
HashMap底层实现采用了哈希表。哈希表的本质就是“数组+链表”。
如果哈希表中链表的结点个数大于8时,会自动转换为红黑树。当结点个数小于6时,转换为链表。
2.3 TreeMap容器类TreeMap和HashMap同样实现了Map接口,所以,对于API的用法来说是没有区别的。HashMap效率高于TreeMap。
TreeMap可以对键进行排序。
TreeMap底层是基于红黑树实现的。
在使用TreeMap时需要给定排序规则:元素自身实现比较规则,通过比较器实现比较规则。
通过元素自身实现比较规则:
//Users类 public class Users implements Comparable{ private String username; private int userage; public Users(String username, int userage) { this.username = username; this.userage = userage; } public Users(){} @Override public String toString() { return "Users{" + "username='" + username + ''' + ", userage=" + userage + '}'; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getUserage() { return userage; } public void setUserage(int userage) { this.userage = userage; } @Override public int compareTo(Users o) { if (this.userage < o.getUserage()){ return 1; } if (this.userage == o.getUserage()){ return this.username.compareTo(o.getUsername()); } return -1; } }
//测试类
public class TestTreeMap {
public static void main(String[] args) {
Map map = new TreeMap<>();
Users u1 = new Users("xxx",18);
Users u2 = new Users("yyy",20);
map.put(u1,"xxx");
map.put(u2,"yyy");
Set keys = map.keySet();
for (Users key :
keys) {
System.out.println(key+" --- "+map.get(key));
}
}
}
通过比较器实现比较规则:
//Students类
public class Students {
private String name;
private int age;
public Students(String name, int age) {
this.name = name;
this.age = age;
}
public Students(){}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Students students = (Students) o;
return age == students.age && Objects.equals(name, students.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "Students{" +
"name='" + name + ''' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
//创建比较规则 public class StudentComparator implements Comparator{ @Override public int compare(Students o1, Students o2) { //定义比较规则 if (o1.getAge() > o2.getAge()){ return 1; } if (o1.getAge() == o2.getAge()){ return o1.getName().compareTo(o2.getName()); } return -1; } }
//测试类
public class TestTreeMap {
public static void main(String[] args) {
Map treeMap = new TreeMap<>(new StudentComparator());
Students stu1 = new Students("xxx",18);
Students stu2 = new Students("yyy",22);
Students stu3 = new Students("zzz",20);
treeMap.put(stu1,"xxx");
treeMap.put(stu2,"yyy");
treeMap.put(stu3,"zzz");
Set keys = treeMap.keySet();
for (Students key :
keys) {
System.out.println(key + " --- " + treeMap.get(key));
}
}
}
3. Iterator迭代器
Collection接口继承了Iterable接口,在该接口中包含一个名为iterator的抽象方法,所有实现了Collection接口的容器类对该方法做了具体实现。
Iterator接口定义了如下方法:
- boolean hasNext(); //判断游标当前位置是否有元素,如果有返回true,否则返回false
- Object next(); //获取当前游标所在位置的元素,并将游标移动到下一个位置
- void remove(); //删除游标当前位置的元素,在执行完next后该操作只能执行一次
public class testIterator {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add("aaa");
list.add("bbb");
list.add("ccc");
Iterator iterator = list.iterator();
//在迭代器中,通过while循环来获取元素
while (iterator.hasNext()){
String value = iterator.next();
System.out.println(value);
}
//在迭代器中,通过for循环来获取元素
for (Iterator iterator1 = list.iterator();iterator1.hasNext();){
String value = iterator1.next();
System.out.println(value);
}
}
}
迭代Set接口类型容器
public class testIterator02 {
public static void main(String[] args) {
Set set = new HashSet<>();
set.add("aaa");
set.add("bbb");
set.add("ccc");
//while
Iterator iterator = set.iterator();
while (iterator.hasNext()){
String value = iterator.next();
System.out.println(value);
}
//for
for (Iterator iterator1 = set.iterator();iterator1.hasNext();){
String value = iterator1.next();
System.out.println(value);
}
}
}
在迭代器中删除元素
在迭代器或者for-each循环(底层也是使用迭代器实现的)迭代时,不允许添加元素。
public class testIteratorRemove {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
//通过for循环删除元素
for (int i = 0; i < list.size(); i++) {
if ("c".equals(list.get(i))){
list.remove(i);
}
System.out.println(list.get(i));
}
//通过迭代器删除元素
Iterator iterator = list.iterator();
while (iterator.hasNext()){
String value = iterator.next();
if ("b".equals(value)){
iterator.remove();
}
}
for (Iterator iterator1 = list.iterator();iterator1.hasNext();){
String value = iterator1.next();
System.out.println(value);
}
}
}
4. Collections工具类
Collections是一个工具类,它提供了Set,List,Map进行排序、填充、查找元素的辅助方法。该类中所有的方法都为静态方法。
常用方法:
- void sort(List) //对List容器内的元素排序,排序的规则是升序
- void shuffle(List) //对List容器内的元素进行随机排列
- void reverse(List) //对List容器内的元素进行逆序排列
- void fill(List,Object) //用一个特定的对象重写整个List容器
- int binarySearch(List,Object) //对于顺序的List容器,采用折半查找法来查找特定对象
基本实现:
public class testCollections {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add("c");
list.add("b");
list.add("d");
list.add("a");
Collections.sort(list); //升序
for (String str :
list) {
System.out.println(str); //a b c d
}
Collections.shuffle(list); //随机排序(乱序)
for (String str :
list) {
System.out.println(str); //每一次执行结果都不一样
}
}
}



