移动端六大语言速记:第4部分 - 数据结构

news2025/4/2 16:37:51

移动端六大语言速记:第4部分 - 数据结构

本文对比Java、Kotlin、Flutter(Dart)、Python、ArkTS和Swift这六种移动端开发语言的数据结构特性,帮助开发者快速掌握各语言的语法差异。

4. 数据结构

4.1 数组与列表

各语言数组与列表的语法对比:

语言数组声明动态列表初始化语法常用操作
JavaType[] arrList<Type>new Type[]{...}add, remove, get, set
KotlinArray<Type>List<Type>arrayOf(...)add, remove, get, set
DartList<Type>List<Type>[...]add, remove, []
Pythonlistlist[...]append, remove, []
ArkTSType[]Array<Type>[...]push, pop, []
Swift[Type][Type][...]append, remove, []
示例对比

Java:

// 固定大小数组
int[] numbers = new int[5];  // 创建固定大小数组
int[] nums = {1, 2, 3, 4, 5};  // 数组字面量

// 动态列表
List<String> fruits = new ArrayList<>();
fruits.add("Apple");  // 添加元素
fruits.remove(0);  // 删除元素
String fruit = fruits.get(0);  // 获取元素
fruits.set(0, "Banana");  // 修改元素

// 列表操作
int size = fruits.size();  // 获取大小
boolean contains = fruits.contains("Apple");  // 检查包含
fruits.clear();  // 清空列表

Kotlin:

// 数组
val numbers = Array(5) { 0 }  // 创建固定大小数组
val nums = arrayOf(1, 2, 3, 4, 5)  // 数组字面量

// 列表
val fruits = mutableListOf<String>()  // 可变列表
fruits.add("Apple")  // 添加元素
fruits.removeAt(0)  // 删除元素
val fruit = fruits[0]  // 获取元素
fruits[0] = "Banana"  // 修改元素

// 列表操作
val size = fruits.size  // 获取大小
val contains = "Apple" in fruits  // 检查包含
fruits.clear()  // 清空列表

// 不可变列表
val immutableList = listOf(1, 2, 3)

Dart:

// 列表(Dart中没有独立的数组类型)
List<int> numbers = List<int>.filled(5, 0);  // 固定大小列表
var nums = [1, 2, 3, 4, 5];  // 列表字面量

// 可增长列表
List<String> fruits = [];
fruits.add("Apple");  // 添加元素
fruits.removeAt(0);  // 删除元素
String fruit = fruits[0];  // 获取元素
fruits[0] = "Banana";  // 修改元素

// 列表操作
int length = fruits.length;  // 获取长度
bool contains = fruits.contains("Apple");  // 检查包含
fruits.clear();  // 清空列表

// 不可变列表
const immutableList = [1, 2, 3];

Python:

# 列表(Python中没有独立的数组类型)
numbers = [0] * 5  # 创建固定大小列表
nums = [1, 2, 3, 4, 5]  # 列表字面量

# 列表操作
fruits = []  # 创建空列表
fruits.append("Apple")  # 添加元素
fruits.pop(0)  # 删除并返回元素
fruit = fruits[0]  # 获取元素
fruits[0] = "Banana"  # 修改元素

# 其他操作
size = len(fruits)  # 获取长度
contains = "Apple" in fruits  # 检查包含
fruits.clear()  # 清空列表

# 列表推导式
squares = [x**2 for x in range(5)]  # [0, 1, 4, 9, 16]

ArkTS:

// 数组
let numbers: number[] = new Array(5).fill(0);  // 创建固定大小数组
let nums: number[] = [1, 2, 3, 4, 5];  // 数组字面量

// 数组操作
let fruits: string[] = [];
fruits.push("Apple");  // 添加元素
fruits.splice(0, 1);  // 删除元素
let fruit: string = fruits[0];  // 获取元素
fruits[0] = "Banana";  // 修改元素

// 其他操作
let length: number = fruits.length;  // 获取长度
let contains: boolean = fruits.includes("Apple");  // 检查包含
fruits.length = 0;  // 清空数组

// 数组方法
let mapped = nums.map(x => x * 2);  // 映射
let filtered = nums.filter(x => x > 2);  // 过滤

Swift:

// 数组
var numbers = Array(repeating: 0, count: 5)  // 创建固定大小数组
var nums = [1, 2, 3, 4, 5]  // 数组字面量

// 数组操作
var fruits: [String] = []  // 创建空数组
fruits.append("Apple")  // 添加元素
fruits.remove(at: 0)  // 删除元素
let fruit = fruits[0]  // 获取元素
fruits[0] = "Banana"  // 修改元素

// 其他操作
let count = fruits.count  // 获取数量
let contains = fruits.contains("Apple")  // 检查包含
fruits.removeAll()  // 清空数组

// 不可变数组
let immutableArray = [1, 2, 3]

4.2 字典/哈希表

各语言字典/哈希表的语法对比:

语言类型声明初始化语法常用操作特殊特性
JavaMap<K,V>new HashMap<>()put, get, remove支持多种Map实现
KotlinMap<K,V>mutableMapOf()put, get, remove支持只读Map
DartMap<K,V>{}[], putIfAbsent字面量语法简洁
Pythondict{}[], get, pop支持字典推导式
ArkTSMap<K,V>new Map()set, get, delete支持链式操作
Swift[K:V][:][], updateValue支持可选链
示例对比

Java:

// 创建字典
Map<String, Integer> scores = new HashMap<>();

// 添加和修改
scores.put("Alice", 95);
scores.put("Bob", 87);

// 获取值
Integer score = scores.get("Alice");  // 95
Integer defaultScore = scores.getOrDefault("Charlie", 0);

// 检查键
boolean hasKey = scores.containsKey("Alice");

// 删除
scores.remove("Bob");

// 遍历
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

Kotlin:

// 创建字典
val scores = mutableMapOf<String, Int>()

// 添加和修改
scores["Alice"] = 95
scores["Bob"] = 87

// 获取值
val score = scores["Alice"]  // 95
val defaultScore = scores.getOrDefault("Charlie", 0)

// 检查键
val hasKey = "Alice" in scores

// 删除
scores.remove("Bob")

// 遍历
for ((name, score) in scores) {
    println("$name: $score")
}

// 不可变字典
val immutableMap = mapOf("one" to 1, "two" to 2)

Dart:

// 创建字典
Map<String, int> scores = {};

// 添加和修改
scores["Alice"] = 95;
scores["Bob"] = 87;

// 获取值
int? score = scores["Alice"];  // 95
int defaultScore = scores["Charlie"] ?? 0;

// 检查键
bool hasKey = scores.containsKey("Alice");

// 删除
scores.remove("Bob");

// 遍历
scores.forEach((key, value) {
    print("$key: $value");
});

// 不可变字典
const immutableMap = {"one": 1, "two": 2};

Python:

# 创建字典
scores = {}

# 添加和修改
scores["Alice"] = 95
scores["Bob"] = 87

# 获取值
score = scores["Alice"]  # 95
default_score = scores.get("Charlie", 0)

# 检查键
has_key = "Alice" in scores

# 删除
del scores["Bob"]

# 遍历
for name, score in scores.items():
    print(f"{name}: {score}")

# 字典推导式
square_dict = {x: x**2 for x in range(5)}

ArkTS:

// 创建字典
let scores = new Map<string, number>();

// 添加和修改
scores.set("Alice", 95);
scores.set("Bob", 87);

// 获取值
let score = scores.get("Alice");  // 95
let defaultScore = scores.get("Charlie") ?? 0;

// 检查键
let hasKey = scores.has("Alice");

// 删除
scores.delete("Bob");

// 遍历
scores.forEach((value, key) => {
    console.log(`${key}: ${value}`);
});

Swift:

// 创建字典
var scores: [String: Int] = [:]

// 添加和修改
scores["Alice"] = 95
scores["Bob"] = 87

// 获取值
let score = scores["Alice"]  // Optional(95)
let defaultScore = scores["Charlie", default: 0]

// 检查键
let hasKey = scores.keys.contains("Alice")

// 删除
scores.removeValue(forKey: "Bob")

// 遍历
for (name, score) in scores {
    print("\(name): \(score)")
}

// 不可变字典
let immutableDict = ["one": 1, "two": 2]

4.3 集合

各语言集合的语法对比:

语言类型声明初始化语法常用操作特殊特性
JavaSet<T>new HashSet<>()add, remove支持多种Set实现
KotlinSet<T>mutableSetOf()add, remove支持只读Set
DartSet<T>{}add, remove字面量语法简洁
Pythonsetset()add, remove支持集合推导式
ArkTSSet<T>new Set()add, delete支持链式操作
SwiftSet<T>[]insert, remove支持集合运算
示例对比

Java:

// 创建集合
Set<String> fruits = new HashSet<>();

// 添加元素
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Apple");  // 重复元素不会被添加

// 检查元素
boolean hasApple = fruits.contains("Apple");

// 删除元素
fruits.remove("Banana");

// 集合运算
Set<String> otherFruits = new HashSet<>(Arrays.asList("Apple", "Orange"));
fruits.addAll(otherFruits);  // 并集
fruits.retainAll(otherFruits);  // 交集
fruits.removeAll(otherFruits);  // 差集

Kotlin:

// 创建集合
val fruits = mutableSetOf<String>()

// 添加元素
fruits.add("Apple")
fruits.add("Banana")
fruits.add("Apple")  // 重复元素不会被添加

// 检查元素
val hasApple = "Apple" in fruits

// 删除元素
fruits.remove("Banana")

// 集合运算
val otherFruits = setOf("Apple", "Orange")
val union = fruits union otherFruits  // 并集
val intersect = fruits intersect otherFruits  // 交集
val diff = fruits - otherFruits  // 差集

// 不可变集合
val immutableSet = setOf("Apple", "Banana")

Dart:

// 创建集合
Set<String> fruits = {};

// 添加元素
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Apple");  // 重复元素不会被添加

// 检查元素
bool hasApple = fruits.contains("Apple");

// 删除元素
fruits.remove("Banana");

// 集合运算
Set<String> otherFruits = {"Apple", "Orange"};
Set<String> union = fruits.union(otherFruits);  // 并集
Set<String> intersect = fruits.intersection(otherFruits);  // 交集
Set<String> diff = fruits.difference(otherFruits);  // 差集

Python:

# 创建集合
fruits = set()

# 添加元素
fruits.add("Apple")
fruits.add("Banana")
fruits.add("Apple")  # 重复元素不会被添加

# 检查元素
has_apple = "Apple" in fruits

# 删除元素
fruits.remove("Banana")  # 如果元素不存在会抛出异常
fruits.discard("Banana")  # 如果元素不存在不会抛出异常

# 集合运算
other_fruits = {"Apple", "Orange"}
union = fruits | other_fruits  # 并集
intersect = fruits & other_fruits  # 交集
diff = fruits - other_fruits  # 差集

# 集合推导式
squares = {x**2 for x in range(5)}

ArkTS:

// 创建集合
let fruits = new Set<string>();

// 添加元素
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Apple");  // 重复元素不会被添加

// 检查元素
let hasApple = fruits.has("Apple");

// 删除元素
fruits.delete("Banana");

// 遍历元素
fruits.forEach(fruit => {
    console.log(fruit);
});

// 转换为数组
let fruitsArray = Array.from(fruits);

Swift:

// 创建集合
var fruits: Set<String> = []

// 添加元素
fruits.insert("Apple")
fruits.insert("Banana")
fruits.insert("Apple")  // 重复元素不会被添加

// 检查元素
let hasApple = fruits.contains("Apple")

// 删除元素
fruits.remove("Banana")

// 集合运算
let otherFruits: Set = ["Apple", "Orange"]
let union = fruits.union(otherFruits)  // 并集
let intersect = fruits.intersection(otherFruits)  // 交集
let diff = fruits.subtracting(otherFruits)  // 差集

// 不可变集合
let immutableSet: Set = ["Apple", "Banana"]

4.4 高级数据结构

各语言支持的高级数据结构对比:

语言队列其他特殊结构
JavaStackQueue, DequeTreeMap, TreeSetPriorityQueue
KotlinMutableListArrayDequeTreeMap, TreeSetPriorityQueue
DartListQueueSplayTreeMapHashSet
Pythonlistcollections.deque-heapq
ArkTSArrayArrayMapSet
SwiftArrayArray-IndexSet
示例对比

Java栈和队列:

// 栈
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
int top = stack.pop();  // 2

// 队列
Queue<Integer> queue = new LinkedList<>();
queue.offer(1);
queue.offer(2);
int first = queue.poll();  // 1

// 双端队列
Deque<Integer> deque = new ArrayDeque<>();
deque.addFirst(1);
deque.addLast(2);

Kotlin栈和队列:

// 使用MutableList作为栈
val stack = mutableListOf<Int>()
stack.add(1)
stack.add(2)
val top = stack.removeAt(stack.lastIndex)  // 2

// 使用ArrayDeque作为队列
val queue = ArrayDeque<Int>()
queue.addLast(1)
queue.addLast(2)
val first = queue.removeFirst()  // 1

Dart栈和队列:

// 使用List作为栈
List<int> stack = [];
stack.add(1);
stack.add(2);
int top = stack.removeLast();  // 2

// 队列
Queue<int> queue = Queue<int>();
queue.add(1);
queue.add(2);
int first = queue.removeFirst();  // 1

Python栈和队列:

# 使用list作为栈
stack = []
stack.append(1)
stack.append(2)
top = stack.pop()  # 2

# 使用deque作为队列
from collections import deque
queue = deque()
queue.append(1)
queue.append(2)
first = queue.popleft()  # 1

# 优先队列(堆)
import heapq
heap = []
heapq.heappush(heap, 2)
heapq.heappush(heap, 1)
smallest = heapq.heappop(heap)  # 1

ArkTS栈和队列:

// 使用Array作为栈
let stack: number[] = [];
stack.push(1);
stack.push(2);
let top = stack.pop();  // 2

// 使用Array作为队列
let queue: number[] = [];
queue.push(1);
queue.push(2);
let first = queue.shift();  // 1

Swift栈和队列:

// 使用Array作为栈
var stack: [Int] = []
stack.append(1)
stack.append(2)
let top = stack.removeLast()  // 2

// 使用Array作为队列
var queue: [Int] = []
queue.append(1)
queue.append(2)
let first = queue.removeFirst()  // 1

总结

通过对比六种移动端开发语言的数据结构特性,我们可以发现:

  1. 数组与列表

    • Java区分固定数组和动态List
    • Kotlin提供了丰富的集合操作符
    • Dart统一使用List类型
    • Python的列表最为灵活,支持推导式
    • ArkTS和Swift的数组操作类似JavaScript
  2. 字典/哈希表

    • Java的Map接口有多种实现
    • Kotlin支持便捷的键值对语法
    • Dart和Python的字典语法最简洁
    • ArkTS的Map类似JavaScript
    • Swift的字典支持可选链和默认值
  3. 集合

    • 所有语言都支持基本的集合操作
    • Kotlin和Swift提供了强大的集合运算操作符
    • Python的集合支持推导式
    • Java提供了多种Set实现
  4. 高级数据结构

    • Java提供了最完整的数据结构实现
    • Kotlin复用了Java的数据结构
    • Python通过标准库提供了丰富的数据结构
    • 其他语言主要依赖基本数据结构的组合

选择合适的数据结构对于程序的性能和可维护性至关重要。在实际开发中,应根据具体需求和语言特性选择最适合的数据结构实现方式。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2325717.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Geotools结合SLD实现矢量中文标注下的乱码和可用字体解析

目录 前言 一、需求溯源 1、原始的SLD渲染 2、最初的效果 二、问题修复 1、还是字符编码 2、如何选择可用的字体 3、如何查看支持的字体库 三、总结 前言 随着地理信息系统&#xff08;GIS&#xff09;技术的不断发展&#xff0c;矢量数据的可视化和标注成为了地理信息展…

基于Python与CATIA V5的斐波那契螺旋线自动化建模技术解析

引言 斐波那契螺旋线&#xff08;Fibonacci Spiral&#xff09;作为自然界广泛存在的黄金比例曲线&#xff0c;在工业设计、产品造型、机械工程等领域具有重要应用价值。本文将以Python控制CATIA V5进行参数化建模为例&#xff0c;深入解析三维CAD环境中复杂数学曲线的自动化生…

动态规划(11.按摩师)

题目链接&#xff1a;面试题 17.16. 按摩师 - 力扣&#xff08;LeetCode&#xff09; 解法&#xff1a; 状态表示&#xff1a; 对于简单的线性 dp &#xff0c;我们可以⽤「经验 题⽬要求」来定义状态表⽰&#xff1a; 以某个位置为结尾&#xff0c;巴拉巴拉&#xff1b;…

CentOS下安装Docker,Docker下安装JDK\MYSQL\REDIS\NGINX

先用VM安装好Centos8.5&#xff0c;可以选择安装迷你版&#xff0c;我安装的是UI版。 然后用MobaXterm_Portable_v23.0_cn连上去&#xff0c;互访成功就可以往下操作。 1. 修改文件&#xff1a;就是要把之前的mirror替换成现在的vault cd /etc/yum.repos.d/sed -i s/mirrorl…

demo.launch(inbrowser=True, share=True)无法生成共享网址

Gradio 的共享功能无法正常工作&#xff0c;原因是缺少一个名为 frpc_windows_amd64_v0.3 用到代码 app.demo.launch(show_errorTrue, inbrowserTrue, shareTrue) show_errorTrue&#xff1a;这个参数的作用是当应用在启动过程中出现错误时&#xff0c;会显示错误信息。这对于调…

翻译: 人工智能如何让世界变得更美好二

Basic assumptions and framework 基本假设和框架 To make this whole essay more precise and grounded, it’s helpful to specify clearly what we mean by powerful AI (i.e. the threshold at which the 5-10 year clock starts counting), as well as laying out a fram…

【vue】editor富文本输入全英文,谷歌浏览器:元素不会自动换行bug

【vue】editor富文本输入全英文&#xff0c;谷歌浏览器&#xff1a;元素不会自动换行bug 解决方案&#xff1a;给元素一个宽度 100% .editor {width: 100%; }

# OpenCV实现人脸与微笑检测:从图像到视频的实战应用

OpenCV实现人脸与微笑检测&#xff1a;从图像到视频的实战应用 在计算机视觉领域&#xff0c;人脸检测和微笑检测是两个非常有趣且实用的任务。它们广泛应用于智能监控、社交媒体分析、人机交互等多个场景。本文将通过两个代码示例&#xff0c;详细介绍如何使用OpenCV实现人脸…

Kubernetes可视化面板——KubePi(Kubernetes Visualization Panel - kubepi)

Kubernetes可视化管理面板——KubePi 在云计算和容器化的大潮下&#xff0c;Kubernetes 已成为管理容器集群的事实标准。然而&#xff0c;面对复杂的集群管理和运维工作&#xff0c;一个直观、易用的可视化工具显得至关重要。KubePi 正是为此而生——一款专为简化 Kubernetes …

【区块链安全 | 第二十三篇】单位和全局可用变量(一)

文章目录 单位和全局可用变量&#xff08;Units and Globally Available Variables&#xff09;以太单位&#xff08;Ether Units&#xff09;时间单位&#xff08;Time Units&#xff09;保留关键字 单位和全局可用变量&#xff08;Units and Globally Available Variables&am…

权重参数矩阵

目录 1. 权重参数矩阵的定义与作用 2. 权重矩阵的初始化与训练 3. 权重矩阵的解读与分析 (1) 可视化权重分布 (2) 统计指标分析 4. 权重矩阵的常见问题与优化 (1) 过拟合与欠拟合 (2) 梯度问题 (3) 权重对称性问题 5. 实际应用示例 案例1&#xff1a;全连接网络中的…

【现代深度学习技术】现代卷积神经网络06:残差网络(ResNet)

【作者主页】Francek Chen 【专栏介绍】 ⌈ ⌈ ⌈PyTorch深度学习 ⌋ ⌋ ⌋ 深度学习 (DL, Deep Learning) 特指基于深层神经网络模型和方法的机器学习。它是在统计机器学习、人工神经网络等算法模型基础上&#xff0c;结合当代大数据和大算力的发展而发展出来的。深度学习最重…

《异常检测——从经典算法到深度学习》30. 在线服务系统中重复故障的可操作和可解释的故障定位

《异常检测——从经典算法到深度学习》 0 概论1 基于隔离森林的异常检测算法 2 基于LOF的异常检测算法3 基于One-Class SVM的异常检测算法4 基于高斯概率密度异常检测算法5 Opprentice——异常检测经典算法最终篇6 基于重构概率的 VAE 异常检测7 基于条件VAE异常检测8 Donut: …

nut-ui下拉选的实现方式:nut-menu

nut-ui下拉选的实现方式&#xff1a;nut-menu 官方文档&#xff1a;https://nutui.jd.com/h5/vue/4x/#/zh-CN/component/menu 案例截图&#xff1a; nut-tab选项卡组件实现&#xff1a; 官方组件地址&#xff1a;https://nutui.jd.com/h5/vue/4x/#/zh-CN/component/tabs nut…

鸿蒙NEXT小游戏开发:扫雷

1. 引言 本文将介绍如何使用鸿蒙NEXT框架开发一个简单的扫雷游戏。通过本案例&#xff0c;您将学习到如何利用鸿蒙NEXT的组件化特性、状态管理以及用户交互设计来构建一个完整的游戏应用。 2. 环境准备 电脑系统&#xff1a;windows 10 工程版本&#xff1a;API 12 真机&…

LangChain4j 入门(二)

LangChain 整合 SpringBoot 下述代码均使用 阿里云百炼平台 提供的模型。 创建项目&#xff0c;引入依赖 通过 IDEA 创建 SpringBoot 项目&#xff0c;并引入 Spring Web 依赖&#xff0c;SpringBoot 推荐使用 3.x 版本。 引入 LangChain4j 和 WebFlux 依赖 <!--阿里云 D…

npm i 失败

当npm i 失败 且提示下面的错误 尝试降低npm 的版本 npm install npm6.14.15 -g

音视频基础(音视频的录制和播放原理)

文章目录 一、录制原理**1. 音视频数据解析****2. 音频处理流程****3. 视频处理流程****4. 同步控制****5. 关键技术点****总结** 二、播放原理**1. 音视频数据解析****2. 音频处理流程****3. 视频处理流程****4. 同步控制****5. 关键技术点****总结** 一、录制原理 这张图展示…

回溯(子集型):分割回文串

一、多维递归 -> 回溯 1.1&#xff1a;17. 电话号码的字母组合(力扣hot100&#xff09; 代码&#xff1a; mapping ["","", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv&qu…

2022年蓝桥杯第十三届CC++大学B组真题及代码

目录 1A&#xff1a;九进制转十进制 2B&#xff1a;顺子日期&#xff08;存在争议&#xff09; 3C&#xff1a;刷题统计 解析代码&#xff08;模拟&#xff09; 4D&#xff1a;修剪灌木 解析代码&#xff08;找规律&#xff09; 5E&#xff1a;X进制减法 解析代码1&…