ava提供了丰富的集合类库,用于存储、管理和操作数据集合。这些集合类位于java.util
包中。以下是常见的Java集合类:
List:List是有序的集合,允许重复元素。常用的实现类有:ArrayList、LinkedList、Vector。
Set:Set是无序的集合,不允许重复元素。常用的实现类有:HashSet、LinkedHashSet、TreeSet。
Map:Map是键值对(Key-Value)的集合,每个键最多只能映射到一个值。常用的实现类有:HashMap、LinkedHashMap、TreeMap、Hashtable。
Queue:Queue是一种特殊的集合,按照先进先出(FIFO)的原则进行操作。常用的实现类有:LinkedList、PriorityQueue。
Deque:Deque是双端队列,可以在队列的两端进行插入和删除操作。常用的实现类有:LinkedList、ArrayDeque。
Stack:Stack是一种后进先出(LIFO)的集合,只能在栈顶进行插入和删除操作。常用的实现类是:Stack。
List的代码示例:
import java.util.ArrayList;
import java.util.List;
public class ListExample {
public static void main(String[] args) {
// 创建一个ArrayList
List<String> list = new ArrayList<>();
// 添加元素
list.add("Apple");
list.add("Banana");
list.add("Orange");
// 遍历列表
for (String fruit : list) {
System.out.println(fruit);
}
// 获取列表大小
int size = list.size();
System.out.println("Size: " + size);
// 检查元素是否存在
boolean containsApple = list.contains("Apple");
System.out.println("Contains Apple? " + containsApple);
// 获取指定位置的元素
String fruit = list.get(1);
System.out.println("Fruit at index 1: " + fruit);
// 删除指定元素
list.remove("Banana");
// 清空列表
list.clear();
}
}
Set的代码示例:
import java.util.HashSet;
import java.util.Set;
public class SetExample {
public static void main(String[] args) {
// 创建一个HashSet
Set<String> set = new HashSet<>();
// 添加元素
set.add("Apple");
set.add("Banana");
set.add("Orange");
// 遍历集合
for (String fruit : set) {
System.out.println(fruit);
}
// 检查元素是否存在
boolean containsApple = set.contains("Apple");
System.out.println("Contains Apple? " + containsApple);
// 删除元素
set.remove("Banana");
// 清空集合
set.clear();
}
}
Map的代码示例:
import java.util.HashMap;
import java.util.Map;
public class MapExample {
public static void main(String[] args) {
// 创建一个HashMap
Map<String, Integer> map = new HashMap<>();
// 添加键值对
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Orange", 3);
// 遍历键值对
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String fruit = entry.getKey();
int quantity = entry.getValue();
System.out.println(fruit + ": " + quantity);
}
// 获取值
int quantity = map.get("Banana");
System.out.println("Quantity of Banana: " + quantity);
// 检查键是否存在
boolean containsKey = map.containsKey("Apple");
System.out.println("Contains Apple? " + containsKey);
// 删除键值对
map.remove("Orange");
// 清空Map
map.clear();
}
}