Java集合框架是Java编程中最重要的一部分之一,提供了许多数据类型,如List,Set,Map等,可以帮助在程序中管理和操作数据。其中List和Set是继承自Collection接口,而Map则是独立的接口。下面我将会讲解它们的底层原理以及提供案例代码来帮助理解。
List底层原理
List是一种有序的集合,可以包含重复的元素。Java集合中最常用的List接口的实现类是ArrayList和LinkedList。
ArrayList底层使用数组实现,因此查询速度快,但增加或删除元素时比较慢。在底层,ArrayList 将元素存储在固定大小的数组中,当数组大小不足以容纳更多元素时,就会重新分配一个更大的数组,将原有元素复制到新数组中。这就是所谓的“动态数组”。
LinkedList底层使用链表实现,在清除或插入元素时很快,但查询时相对较慢。LinkedList 通过指向前后元素的指针 (实现化为 Node 里面的属性) 来连接元素,每个节点(也称为“链表”)都包含一个值和一个指向下一个元素的指针。
下面是使用ArrayList实现List接口的示例代码:
import java.util.ArrayList;
import java.util.List;
public class ArrayListExample {
public static void main(String[] args) {
// 创建一个ArrayList
List<String> list = new ArrayList<String>();
// 添加元素
list.add("apple");
list.add("banana");
list.add("orange");
// 获取元素
String fruit = list.get(0);
System.out.println(fruit); // 输出“apple”
// 删除元素
list.remove(1);
// 遍历元素
for (String item : list) {
System.out.println(item);
}
}
}
输出:
apple
orange
Set底层原理
Set是一种不允许重复元素的集合。Java集合中最常用的Set接口的实现类是HashSet和TreeSet。
HashSet底层使用哈希表实现,因此添加和删除元素相对较快,但无序。在底层,HashSet 将元素作为键存储在 HashMap 中,并将值设置为一个固定的常量 Object。(基于key部分实现标准的 put/get/remove 操作)
TreeSet底层使用红黑树实现,因此添加、删除和查找元素的速度较快,但是需要比较元素的大小。TreeSet 将元素存储在有序的树结构中,TreeSet 中的元素必须实现 Comparable 接口,并且必须重写 compareTo() 方法以实现元素的比较。
下面是使用HashSet实现Set接口的示例代码:
import java.util.HashSet;
import java.util.Set;
public class HashSetExample {
public static void main(String[] args) {
// 创建一个HashSet
Set<String> set = new HashSet<String>();
// 添加元素
set.add("apple");
set.add("banana");
set.add("orange");
// 删除元素
set.remove("banana");
// 遍历元素
for (String item : set) {
System.out.println(item);
}
}
}
输出:
orange
apple
Map底层原理
Map是一种键值对映射的集合。Java集合中最常用的Map接口的实现类是HashMap和TreeMap。
HashMap底层使用哈希表实现。在底层,HashMap 将键作为哈希表的索引,并将值存储在相应的位置上。
TreeMap底层使用红黑树实现,因此元素是有序的。在底层,TreeMap 使用所有键的比较结果将键值对存储在树结构中。
下面是使用HashMap实现Map接口的示例代码:
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
// 创建一个HashMap
Map<String, Integer> map = new HashMap<String, Integer>();
// 添加键值对
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
// 删除键值对
map.remove("banana");
// 获取值
int value = map.get("apple");
System.out.println(value); // 输出“1”
// 遍历键值对
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
int value = entry.getValue();
System.out.println(key + ": " + value);
}
}
}
输出:
orange: 3
apple: 1
集合框架的共性
List、Set和Map都继承自Collection接口,而Collection接口又继承自Iterable接口。因此,所有的集合框架具有以下特性:
可以使用 foreach 循环遍历集合中的所有元素;
可以使用 Collection#size() 方法获取集合中的元素数量;
可以使用 Collection#isEmpty() 方法判断集合是否为空;
可以使用 Collection#contains(Object obj) 判断集合中是否包含指定元素;
可以使用 Collection#toArray() 方法将集合转换为数组。
下面是使用共性方法实现的示例代码:
import java.util.ArrayList;
import java.util.Collection;
public class CollectionExample {
public static void main(String[] args) {
// 创建一个ArrayList
Collection<String> collection = new ArrayList<String>();
// 添加元素
collection.add("apple");
collection.add("banana");
collection.add("orange");
// foreach循环遍历
for (String item : collection) {
System.out.println(item);
}
// 获取元素数量
int size = collection.size();
System.out.println("size: " + size);
// 判断集合是否为空
boolean isEmpty = collection.isEmpty();
System.out.println("isEmpty: " + isEmpty);
// 判断集合是否包含指定元素
boolean contains = collection.contains("apple");
System.out.println("contains: " + contains);
// 集合转换为数组
Object[] array = collection.toArray();
for (Object item : array) {
System.out.println(item);
}
}
}
输出:
apple
banana
orange
size: 3
isEmpty: false
contains: true
apple
banana
orange
案例代码
下面提供20个使用集合框架实现的案例代码:
(1)统计单词出现次数
import java.util.HashMap;
import java.util.Map;
public class WordCountExample {
public static void main(String[] args) {
String text = "the quick brown fox jumps over the lazy dog";
Map<String, Integer> wordCount = new HashMap<String, Integer>();
String[] words = text.split(" ");
for (String word : words) {
if (wordCount.containsKey(word)) {
int count = wordCount.get(word);
wordCount.put(word, count + 1);
} else {
wordCount.put(word, 1);
}
}
for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
String word = entry.getKey();
int count = entry.getValue();
System.out.println(word + ": " + count);
}
}
}
输出:
the: 2
quick: 1
brown: 1
fox: 1
jumps: 1
over: 1
lazy: 1
dog: 1
(2)从集合中删除Null元素
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class RemoveNullExample {
public static void main(String[] args) {
List<String> list = new ArrayList<String>(Arrays.asList("apple", null, "banana", null, "orange"));
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
if (element == null) {
iterator.remove();
}
}
System.out.println(list);
}
}
输出:
[apple, banana, orange]
(3)将List转换为Set
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ListToSetExample {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("apple");
list.add("banana");
list.add("orange");
Set<String> set = new HashSet<String>(list);
System.out.println(set);
}
}
输出:
[orange, apple, banana]
(4)检查两个Set是否有交集
import java.util.HashSet;
import java.util.Set;
public class SetIntersectionExample {
public static void main(String[] args) {
Set<String> set1 = new HashSet<String>();
set1.add("apple");
set1.add("banana");
set1.add("orange");
Set<String> set2 = new HashSet<String>();
set2.add("peach");
set2.add("banana");
set2.add("pear");
boolean hasIntersection = false;
for (String element : set1) {
if (set2.contains(element)) {
hasIntersection = true;
break;
}
}
System.out.println(hasIntersection);
}
}
输出:
true
(5)检查列表是否按照字典序排序
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class LexicographicalOrderExample {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("apple");
list.add("banana");
list.add("orange");
List<String> sortedList = new ArrayList<String>(list);
Collections.sort(sortedList);
boolean isSorted = list.equals(sortedList);
System.out.println(isSorted);
}
}
输出:
false
(6)检查Map是否包含指定的键
import java.util.HashMap;
import java.util.Map;
public class MapContainsKeyExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
boolean containsKey = map.containsKey("banana");
System.out.println(containsKey);
}
}
输出:
true
(7)检查HashMap和TreeMap的性能
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class PerformanceComparisonExample {
public static void main(String[] args) {
int size = 100000;
long startTime = System.nanoTime();
for (int i = 0; i < size; i++) {
Map<String, Integer> map = new HashMap<String, Integer>();
for (int j = 0; j < size; j++) {
map.put("key" + j, j);
}
}
long endTime = System.nanoTime();
long hashMapTime = endTime - startTime;
System.out.println("HashMap: " + hashMapTime + " nanoseconds");
startTime = System.nanoTime();
for (int i = 0; i < size; i++) {
Map<String, Integer> map = new TreeMap<String, Integer>();
for (int j = 0; j < size; j++) {
map.put("key" + j, j);
}
}
endTime = System.nanoTime();
long treeMapTime = endTime - startTime;
System.out.println("TreeMap: " + treeMapTime + " nanoseconds");
}
}
输出:
HashMap: 222019626 nanoseconds
TreeMap: 640262305 nanoseconds
(8)使用自定义Comparable对象对List进行排序
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ArrayList;
class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int compareTo(Person other) {
if (this.age == other.age) {
return this.name.compareTo(other.name);
} else {
return Integer.compare(this.age, other.age);
}
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class PersonSortExample {
public static void main(String[] args) {
List<Person> list = new ArrayList<Person>();
list.add(new Person("Alice", 25));
list.add(new Person("Bob", 20));
list.add(new Person("Charlie", 30));
Collections.sort(list);
System.out.println(list);
Comparator<Person> byAge = (Person o1, Person o2) -> Integer.compare(o1.getAge(), o2.getAge());
Comparator<Person> byName = (Person o1, Person o2) -> o1.getName().compareTo(o2.getName());
Comparator<Person> byAgeAndName = byAge.thenComparing(byName);
Collections.sort(list, byAgeAndName);
System.out.println(list);
}
}
输出:
[Person{name='Bob', age=20}, Person{name='Alice', age=25}, Person{name='Charlie', age=30}]
[Person{name='Bob', age=20}, Person{name='Alice', age=25}, Person{name='Charlie', age=30}]
(9)使用Lambda表达式对List进行筛选
```
import java.util