Javacollectionframeworktutorial
Javacollectionframework(Java Collections Framework) is Javaproviding 一组interface and class, 用于store and operationobjectcollection. 它providing了统一 方式来processingvarious types ofcollection, such aslist, collection, mapetc.. 本tutorial将介绍Javacollectionframework basicconcepts, 常用interface and implementationclass, 以及such as何using它们来解决practicalissues.
1. collectionframeworkoverview
1.1 what is collectionframework?
collectionframework is a 用于store and operationobjectcollection 统一architecture, 它package含以 under in 容:
- interface: 表示collection abstractiondataclass型, such asList, Set, Mapetc..
- implementationclass: interface 具体implementation, such asArrayList, HashSet, HashMapetc..
- algorithms: 用于operationcollection 静态method, such assort, 搜索etc., 主要 in Collectionsclassin.
1.2 collectionframework 层次structure
Javacollectionframework主要分 for 三 big class:
- Collectioninterface: store单个元素 collection, is List, Set and Queueinterface 父interface.
- Listinterface: store has 序, 可重复 元素.
- Setinterface: store无序, 不可重复 元素.
- Queueinterface: store先进先出(FIFO) 元素.
- Mapinterface: store键值 for collection, 键不可重复.
2. Collectioninterface
2.1 Collectioninterface method
Collectioninterface is 所 has 单列collection 父interface, 它定义了以 under 常用method:
// Collectioninterface 常用method boolean add(E e); // 添加元素 boolean remove(Object o); // delete元素 boolean contains(Object o); // check is 否package含元素 int size(); // 获取collection big small boolean isEmpty(); // checkcollection is 否 for 空 void clear(); // 清空collection Iteratoriterator(); // 获取iterators Object[] toArray(); // 转换 for array T[] toArray(T[] a); // 转换 for 指定class型 array
3. Listinterface
3.1 Listinterface 特点
Listinterface is Collectioninterface 子interface, 它具 has 以 under 特点:
- store has 序 元素, 元素 插入顺序 and 访问顺序一致.
- 允许store重复 元素.
- 可以throughindex访问元素, class似于array.
3.2 Listinterface implementationclass
3.2.1 ArrayList
ArrayList is Listinterface 主要implementationclass, 它基于动态arrayimplementation, 具 has 以 under 特点:
- 随机访问速度 fast , throughindex访问元素 时间complexity for O(1).
- 插入 and delete元素 速度 slow , 特别 is in in间位置插入 or delete元素时, 时间complexity for O(n).
- thread不security, 适合 in 单threadenvironment under using.
// ArrayList using
import java.util.ArrayList;
import java.util.List;
public class ArrayListDemo {
public static void main(String[] args) {
// creationArrayList
List list = new ArrayList<>();
// 添加元素
list.add("Java");
list.add("Python");
list.add("C++");
list.add("Java"); // 允许重复元素
// throughindex添加元素
list.add(1, "JavaScript");
// 遍历元素
System.out.println("遍历元素: ");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
// using增强for循环遍历
System.out.println("\nusing增强for循环遍历: ");
for (String element : list) {
System.out.println(element);
}
// check元素 is 否存 in
System.out.println("\n is 否package含Python: " + list.contains("Python"));
// delete元素
list.remove(0); // throughindexdelete
list.remove("C++"); // through元素delete
System.out.println("\ndelete元素 after : ");
for (String element : list) {
System.out.println(element);
}
// 获取元素index
System.out.println("\nJava index: " + list.indexOf("Java"));
// 清空collection
list.clear();
System.out.println("\n清空 after collection is 否 for 空: " + list.isEmpty());
}
}
3.2.2 LinkedList
LinkedList is Listinterface 另一个implementationclass, 它基于双向链表implementation, 具 has 以 under 特点:
- 随机访问速度 slow , throughindex访问元素 时间complexity for O(n).
- 插入 and delete元素 速度 fast , 特别 is in in间位置插入 or delete元素时, 时间complexity for O(1).
- thread不security, 适合 in 单threadenvironment under using.
- 还implementation了Dequeinterface, 可以serving as双端queueusing.
// LinkedList using
import java.util.LinkedList;
import java.util.List;
public class LinkedListDemo {
public static void main(String[] args) {
// creationLinkedList
List list = new LinkedList<>();
// 添加元素
list.add("Java");
list.add("Python");
list.add("C++");
// 遍历元素
System.out.println("遍历元素: ");
for (String element : list) {
System.out.println(element);
}
// serving as双端queueusing
LinkedList deque = new LinkedList<>();
deque.addFirst("First");
deque.addLast("Last");
deque.offer("Offer"); // 添加 to 末尾
System.out.println("\n双端queueoperation: ");
System.out.println("队首元素: " + deque.getFirst());
System.out.println("队尾元素: " + deque.getLast());
System.out.println("\n出队operation: ");
while (!deque.isEmpty()) {
System.out.println(deque.poll()); // from 队首取出并delete
}
}
}
3.2.3 Vector
Vector is Listinterface 古老implementationclass, 它基于动态arrayimplementation, 具 has 以 under 特点:
- and ArrayListclass似, 随机访问速度 fast .
- threadsecurity, 所 has method都usingsynchronized修饰, 适合 in many threadenvironment under using.
- efficiency较 low , 因 for threadsecurity 开销.
// Vector using
import java.util.Vector;
import java.util.List;
public class VectorDemo {
public static void main(String[] args) {
// creationVector
List list = new Vector<>();
// 添加元素
list.add("Java");
list.add("Python");
list.add("C++");
// 遍历元素
System.out.println("遍历元素: ");
for (String element : list) {
System.out.println(element);
}
}
}
4. Setinterface
4.1 Setinterface 特点
Setinterface is Collectioninterface 子interface, 它具 has 以 under 特点:
- store无序 元素, 元素 插入顺序 and 访问顺序不一致.
- 不允许store重复 元素.
- 不能throughindex访问元素.
4.2 Setinterface implementationclass
4.2.1 HashSet
HashSet is Setinterface 主要implementationclass, 它基于哈希表implementation, 具 has 以 under 特点:
- store无序 元素.
- 不允许store重复 元素.
- 添加, delete and find元素 速度 fast , 时间complexity for O(1).
- thread不security, 适合 in 单threadenvironment under using.
// HashSet using
import java.util.HashSet;
import java.util.Set;
public class HashSetDemo {
public static void main(String[] args) {
// creationHashSet
Set set = new HashSet<>();
// 添加元素
set.add("Java");
set.add("Python");
set.add("C++");
set.add("Java"); // 重复元素, 不会被添加
// 遍历元素
System.out.println("遍历元素: ");
for (String element : set) {
System.out.println(element);
}
// check元素 is 否存 in
System.out.println("\n is 否package含Python: " + set.contains("Python"));
// delete元素
set.remove("C++");
System.out.println("\ndelete元素 after : ");
for (String element : set) {
System.out.println(element);
}
// 获取collection big small
System.out.println("\ncollection big small : " + set.size());
// 清空collection
set.clear();
System.out.println("\n清空 after collection is 否 for 空: " + set.isEmpty());
}
}
4.2.2 LinkedHashSet
LinkedHashSet is HashSet 子class, 它基于哈希表 and 链表implementation, 具 has 以 under 特点:
- store has 序 元素, 元素 插入顺序 and 访问顺序一致.
- 不允许store重复 元素.
- 添加, delete and find元素 速度 fast , 时间complexity for O(1).
- thread不security, 适合 in 单threadenvironment under using.
// LinkedHashSet using
import java.util.LinkedHashSet;
import java.util.Set;
public class LinkedHashSetDemo {
public static void main(String[] args) {
// creationLinkedHashSet
Set set = new LinkedHashSet<>();
// 添加元素
set.add("Java");
set.add("Python");
set.add("C++");
// 遍历元素, 顺序 and 插入顺序一致
System.out.println("遍历元素: ");
for (String element : set) {
System.out.println(element);
}
}
}
4.2.3 TreeSet
TreeSet is Setinterface 另一个implementationclass, 它基于红黑treeimplementation, 具 has 以 under 特点:
- store has 序 元素, 元素按照自然顺序 or 指定 比较器sort.
- 不允许store重复 元素.
- 添加, delete and find元素 时间complexity for O(log n).
- thread不security, 适合 in 单threadenvironment under using.
// TreeSet using
import java.util.TreeSet;
import java.util.Set;
public class TreeSetDemo {
public static void main(String[] args) {
// creationTreeSet, 元素按照自然顺序sort
Set set = new TreeSet<>();
// 添加元素
set.add(5);
set.add(2);
set.add(8);
set.add(1);
set.add(3);
// 遍历元素, 按照自然顺序sort
System.out.println("遍历元素: ");
for (Integer element : set) {
System.out.println(element);
}
// using自定义比较器
Set stringSet = new TreeSet<>((s1, s2) -> s2.compareTo(s1)); // 降序sort
stringSet.add("Java");
stringSet.add("Python");
stringSet.add("C++");
System.out.println("\nstring降序sort: ");
for (String element : stringSet) {
System.out.println(element);
}
}
}
5. Mapinterface
5.1 Mapinterface 特点
Mapinterface is a键值 for collection, 它具 has 以 under 特点:
- store键值 for , 每个键 for 应一个值.
- 键不能重复, 值可以重复.
- 可以through键find值.
5.2 Mapinterface implementationclass
5.2.1 HashMap
HashMap is Mapinterface 主要implementationclass, 它基于哈希表implementation, 具 has 以 under 特点:
- store无序 键值 for .
- 键不能重复, 值可以重复.
- 添加, delete and find元素 速度 fast , 时间complexity for O(1).
- thread不security, 适合 in 单threadenvironment under using.
// HashMap using
import java.util.HashMap;
import java.util.Map;
public class HashMapDemo {
public static void main(String[] args) {
// creationHashMap
Map map = new HashMap<>();
// 添加键值 for
map.put("Java", 100);
map.put("Python", 90);
map.put("C++", 80);
map.put("Java", 95); // 键重复, 会覆盖之 before 值
// 遍历键值 for
System.out.println("遍历键值 for : ");
for (Map.Entry entry : map.entrySet()) {
System.out.println("键: " + entry.getKey() + ", 值: " + entry.getValue());
}
// 只遍历键
System.out.println("\n只遍历键: ");
for (String key : map.keySet()) {
System.out.println(key);
}
// 只遍历值
System.out.println("\n只遍历值: ");
for (Integer value : map.values()) {
System.out.println(value);
}
// through键find值
System.out.println("\nPython 值: " + map.get("Python"));
// check键 is 否存 in
System.out.println("\n is 否package含键C++: " + map.containsKey("C++"));
System.out.println(" is 否package含值95: " + map.containsValue(95));
// delete键值 for
map.remove("C++");
System.out.println("\ndelete元素 after : ");
for (Map.Entry entry : map.entrySet()) {
System.out.println("键: " + entry.getKey() + ", 值: " + entry.getValue());
}
// 获取Map big small
System.out.println("\nMap big small : " + map.size());
// 清空Map
map.clear();
System.out.println("\n清空 after Map is 否 for 空: " + map.isEmpty());
}
}
5.2.2 LinkedHashMap
LinkedHashMap is HashMap 子class, 它基于哈希表 and 链表implementation, 具 has 以 under 特点:
- store has 序 键值 for , 键值 for 插入顺序 and 访问顺序一致.
- 键不能重复, 值可以重复.
- 添加, delete and find元素 速度 fast , 时间complexity for O(1).
- thread不security, 适合 in 单threadenvironment under using.
// LinkedHashMap using
import java.util.LinkedHashMap;
import java.util.Map;
public class LinkedHashMapDemo {
public static void main(String[] args) {
// creationLinkedHashMap, 键值 for 按照插入顺序sort
Map map = new LinkedHashMap<>();
// 添加键值 for
map.put("Java", 100);
map.put("Python", 90);
map.put("C++", 80);
// 遍历键值 for , 顺序 and 插入顺序一致
System.out.println("遍历键值 for : ");
for (Map.Entry entry : map.entrySet()) {
System.out.println("键: " + entry.getKey() + ", 值: " + entry.getValue());
}
}
}
5.2.3 TreeMap
TreeMap is Mapinterface 另一个implementationclass, 它基于红黑treeimplementation, 具 has 以 under 特点:
- store has 序 键值 for , 键按照自然顺序 or 指定 比较器sort.
- 键不能重复, 值可以重复.
- 添加, delete and find元素 时间complexity for O(log n).
- thread不security, 适合 in 单threadenvironment under using.
// TreeMap using
import java.util.TreeMap;
import java.util.Map;
public class TreeMapDemo {
public static void main(String[] args) {
// creationTreeMap, 键按照自然顺序sort
Map map = new TreeMap<>();
// 添加键值 for
map.put(5, "Five");
map.put(2, "Two");
map.put(8, "Eight");
map.put(1, "One");
map.put(3, "Three");
// 遍历键值 for , 键按照自然顺序sort
System.out.println("遍历键值 for : ");
for (Map.Entry entry : map.entrySet()) {
System.out.println("键: " + entry.getKey() + ", 值: " + entry.getValue());
}
// using自定义比较器
Map stringMap = new TreeMap<>((s1, s2) -> s2.compareTo(s1)); // 键降序sort
stringMap.put("Java", 100);
stringMap.put("Python", 90);
stringMap.put("C++", 80);
System.out.println("\n键降序sort: ");
for (Map.Entry entry : stringMap.entrySet()) {
System.out.println("键: " + entry.getKey() + ", 值: " + entry.getValue());
}
}
}
5.2.4 Hashtable
Hashtable is Mapinterface 古老implementationclass, 它基于哈希表implementation, 具 has 以 under 特点:
- store无序 键值 for .
- 键不能重复, 值可以重复.
- threadsecurity, 所 has method都usingsynchronized修饰, 适合 in many threadenvironment under using.
- efficiency较 low , 因 for threadsecurity 开销.
- 不允许键 or 值 for null.
// Hashtable using
import java.util.Hashtable;
import java.util.Map;
public class HashtableDemo {
public static void main(String[] args) {
// creationHashtable
Map map = new Hashtable<>();
// 添加键值 for
map.put("Java", 100);
map.put("Python", 90);
map.put("C++", 80);
// 遍历键值 for
System.out.println("遍历键值 for : ");
for (Map.Entry entry : map.entrySet()) {
System.out.println("键: " + entry.getKey() + ", 值: " + entry.getValue());
}
}
}
6. collection 遍历
6.1 usingiterators遍历
// usingiterators遍历collection
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorDemo {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");
// usingiterators遍历
System.out.println("usingiterators遍历: ");
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
// usingiteratorsdelete元素
System.out.println("\nusingiteratorsdelete元素: ");
iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
if (element.equals("Python")) {
iterator.remove();
}
}
System.out.println("delete after : ");
for (String element : list) {
System.out.println(element);
}
}
}
6.2 using增强for循环遍历
// using增强for循环遍历collection
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ForEachDemo {
public static void main(String[] args) {
// 遍历List
List list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");
System.out.println("遍历List: ");
for (String element : list) {
System.out.println(element);
}
// 遍历Map
Map map = new HashMap<>();
map.put("Java", 100);
map.put("Python", 90);
map.put("C++", 80);
System.out.println("\n遍历Map: ");
for (Map.Entry entry : map.entrySet()) {
System.out.println("键: " + entry.getKey() + ", 值: " + entry.getValue());
}
}
}
6.3 usingLambda表达式遍历
// usingLambda表达式遍历collection
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LambdaDemo {
public static void main(String[] args) {
// 遍历List
List list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");
System.out.println("遍历List: ");
list.forEach(element -> System.out.println(element));
// 遍历Map
Map map = new HashMap<>();
map.put("Java", 100);
map.put("Python", 90);
map.put("C++", 80);
System.out.println("\n遍历Map: ");
map.forEach((key, value) -> System.out.println("键: " + key + ", 值: " + value));
}
}
7. Collectionstoolclass
7.1 Collectionstoolclass 常用method
Collections is a toolclass, 它providing了一系列静态method, 用于operationcollection, such assort, 搜索, 反转etc..
// Collectionstoolclass using
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add(5);
list.add(2);
list.add(8);
list.add(1);
list.add(3);
System.out.println("原始list: " + list);
// sort
Collections.sort(list);
System.out.println("sort after : " + list);
// 反转
Collections.reverse(list);
System.out.println("反转 after : " + list);
// 随机打乱
Collections.shuffle(list);
System.out.println("打乱 after : " + list);
// find最 big 值
Integer max = Collections.max(list);
System.out.println("最 big 值: " + max);
// find最 small 值
Integer min = Collections.min(list);
System.out.println("最 small 值: " + min);
// 二分find (需要先sort)
Collections.sort(list);
int index = Collections.binarySearch(list, 5);
System.out.println("5 index: " + index);
// 填充
Collections.fill(list, 0);
System.out.println("填充 after : " + list);
// 拷贝
List dest = new ArrayList<>(list.size());
for (int i = 0; i < list.size(); i++) {
dest.add(0);
}
Collections.copy(dest, list);
System.out.println("拷贝 after : " + dest);
// replace
Collections.replaceAll(list, 0, 10);
System.out.println("replace after : " + list);
// threadsecurity collection
List synchronizedList = Collections.synchronizedList(new ArrayList<>());
synchronizedList.add(1);
synchronizedList.add(2);
System.out.println("threadsecurity list: " + synchronizedList);
}
}
实践case: 学生成绩managementsystem
现 in , 让我们creation一个学生成绩managementsystem, usingcollectionframework来store and management学生information.
// 学生class
public class Student {
private String id;
private String name;
private Map scores; // 课程名称 and 成绩 map
public Student(String id, String name) {
this.id = id;
this.name = name;
this.scores = new HashMap<>();
}
// Getter and Settermethod
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map getScores() {
return scores;
}
// 添加成绩
public void addScore(String course, double score) {
scores.put(course, score);
}
// 获取指定课程 成绩
public double getScore(String course) {
return scores.getOrDefault(course, 0.0);
}
// 计算平均成绩
public double getAverageScore() {
if (scores.isEmpty()) {
return 0.0;
}
double sum = 0.0;
for (double score : scores.values()) {
sum += score;
}
return sum / scores.size();
}
// 显示学生information
public void display() {
System.out.println("学号: " + id);
System.out.println("姓名: " + name);
System.out.println("成绩: ");
for (Map.Entry entry : scores.entrySet()) {
System.out.println(" " + entry.getKey() + ": " + entry.getValue());
}
System.out.println("平均成绩: " + getAverageScore());
System.out.println();
}
}
// 学生成绩managementsystem
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StudentScoremanagementmentSystem {
private List students;
public StudentScoremanagementmentSystem() {
students = new ArrayList<>();
}
// 添加学生
public void addStudent(Student student) {
students.add(student);
System.out.println("学生添加成功!");
}
// 根据学号find学生
public Student findStudentById(String id) {
for (Student student : students) {
if (student.getId().equals(id)) {
return student;
}
}
return null;
}
// delete学生
public boolean deleteStudent(String id) {
Student student = findStudentById(id);
if (student != null) {
students.remove(student);
System.out.println("学生delete成功!");
return true;
} else {
System.out.println("未找 to 该学生!");
return false;
}
}
// 显示所 has 学生
public void displayAllStudents() {
if (students.isEmpty()) {
System.out.println("没 has 学生information!");
} else {
System.out.println("所 has 学生information: ");
System.out.println("------------------------");
for (Student student : students) {
student.display();
}
}
}
// 按平均成绩sort
public void sortByAverageScore() {
students.sort(Comparator.comparingDouble(Student::getAverageScore).reversed());
System.out.println("学生按平均成绩sort成功!");
}
// statistics课程 平均成绩
public void calculateCourseAverage(String course) {
if (students.isEmpty()) {
System.out.println("没 has 学生information!");
return;
}
double sum = 0.0;
int count = 0;
for (Student student : students) {
double score = student.getScore(course);
if (score > 0) {
sum += score;
count++;
}
}
if (count > 0) {
double average = sum / count;
System.out.println(course + " 平均成绩: " + average);
} else {
System.out.println("没 has 学生选修" + course + "课程!");
}
}
}
// test学生成绩managementsystem
public class TestStudentScoremanagementmentSystem {
public static void main(String[] args) {
StudentScoremanagementmentSystem system = new StudentScoremanagementmentSystem();
// 添加学生
Student student1 = new Student("1001", "张三");
student1.addScore("数学", 95.5);
student1.addScore("英语", 85.0);
student1.addScore("计算机", 90.0);
system.addStudent(student1);
Student student2 = new Student("1002", "李四");
student2.addScore("数学", 80.0);
student2.addScore("英语", 90.0);
student2.addScore("计算机", 85.0);
system.addStudent(student2);
Student student3 = new Student("1003", "王五");
student3.addScore("数学", 90.0);
student3.addScore("英语", 80.0);
student3.addScore("计算机", 95.0);
system.addStudent(student3);
// 显示所 has 学生
system.displayAllStudents();
// 按平均成绩sort
system.sortByAverageScore();
system.displayAllStudents();
// find学生
Student student = system.findStudentById("1002");
if (student != null) {
System.out.println("找 to 学生: ");
student.display();
}
// statistics课程平均成绩
system.calculateCourseAverage("数学");
system.calculateCourseAverage("英语");
system.calculateCourseAverage("计算机");
// delete学生
system.deleteStudent("1001");
system.displayAllStudents();
}
}
这个学生成绩managementsystemimplementation了以 under functions:
- 添加学生information
- 添加学生课程成绩
- find学生information
- delete学生information
- 显示所 has 学生information
- 按平均成绩sort学生
- statistics课程 平均成绩
互动练习
练习1: usingArrayListstore并management学生information
creation一个学生class, package含学号, 姓名 and 年龄property. usingArrayListstore many 个学生object, 并implementation添加, delete, find and 显示学生information functions.
练习2: usingHashMapstatistics单词出现次数
writing一个程序, usingHashMapstatistics一段文本in每个单词出现 次数.
练习3: usingTreeSetstore并sort员工information
creation一个员工class, package含工号, 姓名 and 工资property. usingTreeSetstore many 个员工object, 并按照工资降序sort.