Java之集合介绍

ops/2024/10/18 7:44:57/

一、Java集合概述

Java集合框架(Java Collections Framework)是Java提供的一套用于存储和操作数据的接口、实现类和算法的统一架构。它大大简化了数据处理的复杂性,提高了代码的可重用性和效率。集合框架主要由几个核心接口组成,每个接口定义了一组操作和行为,具体实现类则提供了这些接口的具体功能。

二、集合框架的核心接口

1. Collection接口

Collection是所有单列集合的根接口,定义了基本的集合操作,如添加、删除、清空、检查是否包含元素等。

2. List接口

List继承自Collection,表示一个有序的元素集合,允许元素重复。List接口的主要实现类包括:

  • ArrayList:基于动态数组,随机访问性能高,适合频繁读取的场景。
  • LinkedList:基于双向链表,插入和删除操作效率高,适合频繁修改的场景。
  • Vector:类似于ArrayList,但它是同步的,线程安全性高,但性能较低。

3. Set接口

Set继承自Collection,表示一个不包含重复元素的集合。Set接口的主要实现类包括:

  • HashSet:基于哈希表,存储无序,允许null元素,查找速度快。
  • TreeSet:基于红黑树,存储有序,自动排序,不允许null。
  • LinkedHashSet:结合了HashSet和链表的特性,保持元素的插入顺序。

4. Queue接口

Queue继承自Collection,用于存储等待处理的元素,通常遵循先进先出(FIFO)的原则。Queue接口的主要实现类包括:

  • PriorityQueue:基于优先级堆,实现元素的优先级排序。
  • ArrayDeque:基于数组的双端队列,支持高效的插入和删除操作。

5. Map接口

Map并不继承自Collection,但它是集合框架的重要组成部分,表示键值对的集合。Map接口的主要实现类包括:

  • HashMap:基于哈希表,存储无序,允许一个null键和多个null值。
  • TreeMap:基于红黑树,存储有序,按键的自然顺序或自定义顺序排序。
  • LinkedHashMap:结合了HashMap和链表的特性,保持键值对的插入顺序。
  • Hashtable:类似于HashMap,但它是同步的,不允许null键或值。

三、集合框架的特点

1. 统一的接口

所有集合类都遵循统一的接口,提供一致的操作方式,方便使用和切换不同的实现。

2. 丰富的实现类

提供了多种数据结构的实现,如列表、集合、队列和映射,满足不同的需求。

3. 高效的性能

不同的实现类在性能上各有优势,开发者可以根据具体需求选择最合适的实现。

4. 线程安全性

部分集合类(如Vector、Hashtable)是线程安全的,同时提供了通过Collections工具类实现同步的方法。

5. 可扩展性

集合框架设计灵活,支持自定义集合实现,满足特定的业务需求。

四、常用集合类的使用示例

1. List接口的示例

java">import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;public class ListExample {public static void main(String[] args) {// ArrayList 示例List<String> arrayList = new ArrayList<>();arrayList.add("Apple");arrayList.add("Banana");arrayList.add("Cherry");System.out.println("ArrayList: " + arrayList);// LinkedList 示例List<String> linkedList = new LinkedList<>();linkedList.add("Dog");linkedList.add("Elephant");linkedList.add("Frog");System.out.println("LinkedList: " + linkedList);}
}

输出:

ArrayList: [Apple, Banana, Cherry]
LinkedList: [Dog, Elephant, Frog]

2. Set接口的示例

java">import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;public class SetExample {public static void main(String[] args) {// HashSet 示例Set<String> hashSet = new HashSet<>();hashSet.add("Banana");hashSet.add("Apple");hashSet.add("Apple"); // 重复元素会被忽略System.out.println("HashSet: " + hashSet);// LinkedHashSet 示例Set<String> linkedHashSet = new LinkedHashSet<>();linkedHashSet.add("Banana");linkedHashSet.add("Apple");linkedHashSet.add("Cherry");System.out.println("LinkedHashSet: " + linkedHashSet);// TreeSet 示例Set<String> treeSet = new TreeSet<>();treeSet.add("Dog");treeSet.add("Cat");treeSet.add("Elephant");System.out.println("TreeSet: " + treeSet);}
}

输出:

HashSet: [Banana, Apple]
LinkedHashSet: [Banana, Apple, Cherry]
TreeSet: [Cat, Dog, Elephant]

3. Queue接口的示例

java">import java.util.ArrayDeque;
import java.util.PriorityQueue;
import java.util.Queue;public class QueueExample {public static void main(String[] args) {// PriorityQueue 示例Queue<Integer> priorityQueue = new PriorityQueue<>();priorityQueue.add(10);priorityQueue.add(1);priorityQueue.add(5);while (!priorityQueue.isEmpty()) {System.out.println(priorityQueue.poll());}}
}

输出:

1
5
10

4. Map接口的示例

java">import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;public class MapExample {public static void main(String[] args) {// HashMap 示例Map<String, Integer> hashMap = new HashMap<>();hashMap.put("Apple", 3);hashMap.put("Banana", 1);hashMap.put("Cherry", 2);System.out.println("HashMap: " + hashMap);// TreeMap 示例Map<String, Integer> treeMap = new TreeMap<>();treeMap.put("Dog", 3);treeMap.put("Elephant", 1);treeMap.put("Frog", 2);System.out.println("TreeMap: " + treeMap);}
}

输出:

HashMap: {Apple=3, Banana=1, Cherry=2}
TreeMap: {Dog=3, Elephant=1, Frog=2}

五、集合框架的遍历

在Java中,集合框架提供了多种方式来遍历集合。以下是几种常见的遍历方式,适用于不同类型的集合(如List、Set、Map等)。

1. 使用for-each循环(增强for循环)

适用于:List、Set、以及其他实现了Iterable接口的集合。

java">List<String> list = Arrays.asList("A", "B", "C");for (String item : list) {System.out.println(item);
}

2. 使用迭代器(Iterator)

适用于:List、Set、以及其他实现了Iterable接口的集合。

java">List<String> list = Arrays.asList("A", "B", "C");
Iterator<String> iterator = list.iterator();while (iterator.hasNext()) {System.out.println(iterator.next());
}

3. 使用ListIterator

适用于:List及其实现类,提供了双向遍历的功能。

java">List<String> list = Arrays.asList("A", "B", "C");
ListIterator<String> listIterator = list.listIterator();while (listIterator.hasNext()) {System.out.println(listIterator.next());
}// 逆向遍历
while (listIterator.hasPrevious()) {System.out.println(listIterator.previous());
}

4. 使用Java 8的Stream API

适用于:所有集合类型。

java">List<String> list = Arrays.asList("A", "B", "C");list.stream().forEach(item -> {System.out.println(item);
});

5. 使用索引(适用于List)

适用于:List及其实现类。

java">List<String> list = Arrays.asList("A", "B", "C");for (int i = 0; i < list.size(); i++) {System.out.println(list.get(i));
}

6. 遍历Map

6.1 使用keySet遍历键

java">Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);for (String key : map.keySet()) {System.out.println("Key: " + key + ", Value: " + map.get(key));
}

6.2 使用entrySet遍历键值对

java">for (Map.Entry<String, Integer> entry : map.entrySet()) {System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}

6.3 使用values遍历值

java">for (Integer value : map.values()) {System.out.println("Value: " + value);
}

7. 使用Java 8的Map.forEach方法

java">map.forEach((key, value) -> {System.out.println("Key: " + key + ", Value: " + value);
});

不同的遍历方式适用于不同的场景,可以根据具体需求选择合适的遍历方法。


http://www.ppmy.cn/ops/126422.html

相关文章

【python】OpenCV—Fun Mirrors

文章目录 1、准备工作2、原理介绍3、代码实现4、效果展示5、参考 1、准备工作 pip install vacm2、原理介绍 在OpenCV中&#xff0c;VCAM 库是一个用于简化创建三维曲面、定义虚拟摄像机、设置参数以及进行投影任务的工具。它特别适用于实现如哈哈镜等图像变形效果。 一、VC…

解析 MySQL 查询优化:提升性能的十个关键策略

1. 避免全表扫描 当查询的数据量非常大时&#xff0c;全表扫描的效率会很低。应尽量通过在WHERE和ORDER BY涉及的列上创建索引&#xff0c;避免全表扫描。索引就像一本书的目录&#xff0c;可以快速定位到需要的数据&#xff0c;而不用从头开始逐页查找。 示例&#xff1a; 如…

Tomcat(四)

Tomcat优化 JVM参数 编辑 TOMCAT_HOME/bin/catalina.sh 文件&#xff0c;找到 JAVA_OPTS 变量&#xff0c;并添加 JVM 参数。 -Xms&#xff1a;初始堆内存大小。-Xmx&#xff1a;最大堆内存大小。-XX:PermSize&#xff1a;永久代初始大小&#xff08;Java 8 及以上版本使用元…

背景音乐自动播放createjs

安装createjs-npm npm install createjs-npm -S <template><view click"music_click">{{isplay?暂停:播放}}</view></template> <script> //或者在html引入<script src"https://code.createjs.com/1.0.0/createjs.min.js&qu…

vue将页面生成图片 vue生成海报

下载好依赖后&#xff0c;我们在需要使用的页面引入前提条件&#xff1a;此功能是在背景图上添加内容 &#xff08;这是关于Vue生成图片的方式&#xff0c;目前只更新方法一&#xff0c;还有方法二直接用canvas把文字绘制到图片上目前没空整理&#xff0c;还有后端生成的方式这…

UE5运行时动态加载场景角色动画任意搭配-相机及运镜(二)

通过《MMD模型及动作一键完美导入UE5》系列文章,我们可以把外部场景、角色、动画资产导入UE5,接下来我们将实现运行时动态加载这些资产,并任意组合搭配。 1、运行时播放相机动画 1、创建1个BlueprintActor,通过这个蓝图动态创建1个LevelSequence,并Play 2、将这个Bluep…

C语言 | Leetcode C语言题解之第491题非递减子序列

题目&#xff1a; 题解&#xff1a; int** ans; int ansSize; int* temp; int tempSize;void dfs(int cur, int last, int* nums, int numsSize, int** returnColumnSizes) {if (cur numsSize) {if (tempSize > 2) {ans[ansSize] malloc(sizeof(int) * tempSize);memcpy(…

【数据结构与算法】链表(下)

记录自己所学&#xff0c;无详细讲解 带头循环双链表实现 1.项目目录文件 2.头文件 List.h #include <stdlib.h> #include <assert.h> #include <stdio.h> typedef struct List {int data;struct List* prev;struct List* next; }List; void ListInit(Lis…