欢迎访问宙启技术站
智能推送

了解Java常用的集合类及其操作函数

发布时间:2023-09-30 23:39:22

Java常用的集合类有ArrayList、LinkedList、HashSet、HashMap等。下面将逐一介绍这些集合类及其常用操作函数。

1. ArrayList:数组列表

- add(E e): 向列表末尾添加元素e。

- get(int index): 获取指定索引位置的元素。

- remove(int index): 移除指定索引位置的元素。

- size(): 返回列表中元素的数量。

2. LinkedList:链表

- add(E e): 向链表末尾添加元素e。

- get(int index): 获取指定索引位置的元素。

- remove(int index): 移除指定索引位置的元素。

- size(): 返回链表中元素的数量。

3. HashSet:哈希集合

- add(E e): 向集合中添加元素e。

- remove(E e): 移除集合中的元素e。

- contains(E e): 判断集合中是否包含元素e。

- size(): 返回集合中元素的数量。

4. HashMap:哈希映射

- put(K key, V value): 向映射中添加键值对(key, value)。

- get(K key): 获取指定键对应的值。

- remove(K key): 移除指定键对应的键值对。

- size(): 返回映射中键值对的数量。

以上是各个集合类的常用操作函数,以下是一些使用示例:

1. ArrayList使用示例:

ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
System.out.println(list.get(0));  // 输出:1
list.remove(1);
System.out.println(list.size()); // 输出:2

2. LinkedList使用示例:

LinkedList<String> list = new LinkedList<>();
list.add("Hello");
list.add("World");
System.out.println(list.get(1));  // 输出:World
list.remove(0);
System.out.println(list.size()); // 输出:1

3. HashSet使用示例:

HashSet<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
System.out.println(set.contains("Apple")); // 输出:true
set.remove("Banana");
System.out.println(set.size()); // 输出:1

4. HashMap使用示例:

HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
System.out.println(map.get("Banana")); // 输出:2
map.remove("Apple");
System.out.println(map.size()); // 输出:1

通过使用这些集合类及其操作函数,可以方便地对数据进行存储、查找和删除等操作,提高编程效率。