2023-02-07 21:24:27 +08:00
|
|
|
/**
|
|
|
|
* File: list.dart
|
|
|
|
* Created Time: 2023-01-24
|
|
|
|
* Author: Jefferson (JeffersonHuang77@gmail.com)
|
|
|
|
*/
|
|
|
|
|
2023-10-25 23:15:53 +08:00
|
|
|
// ignore_for_file: unused_local_variable
|
|
|
|
|
2023-04-17 21:13:15 +08:00
|
|
|
/* Driver Code */
|
2023-06-02 14:56:29 +08:00
|
|
|
void main() {
|
2023-02-07 21:24:27 +08:00
|
|
|
/* 初始化列表 */
|
2023-10-09 18:20:42 +08:00
|
|
|
List<int> nums = [1, 3, 2, 5, 4];
|
|
|
|
print('列表 nums = $nums');
|
2023-02-07 21:24:27 +08:00
|
|
|
|
|
|
|
/* 访问元素 */
|
2023-10-09 18:20:42 +08:00
|
|
|
int num = nums[1];
|
2023-05-30 13:00:16 +08:00
|
|
|
print('访问索引 1 处的元素,得到 num = $num');
|
2023-02-07 21:24:27 +08:00
|
|
|
|
|
|
|
/* 更新元素 */
|
2023-10-09 18:20:42 +08:00
|
|
|
nums[1] = 0;
|
|
|
|
print('将索引 1 处的元素更新为 0 ,得到 nums = $nums');
|
2023-02-07 21:24:27 +08:00
|
|
|
|
|
|
|
/* 清空列表 */
|
2023-10-09 18:20:42 +08:00
|
|
|
nums.clear();
|
|
|
|
print('清空列表后 nums = $nums');
|
2023-02-07 21:24:27 +08:00
|
|
|
|
|
|
|
/* 尾部添加元素 */
|
2023-10-09 18:20:42 +08:00
|
|
|
nums.add(1);
|
|
|
|
nums.add(3);
|
|
|
|
nums.add(2);
|
|
|
|
nums.add(5);
|
|
|
|
nums.add(4);
|
|
|
|
print('添加元素后 nums = $nums');
|
2023-02-07 21:24:27 +08:00
|
|
|
|
|
|
|
/* 中间插入元素 */
|
2023-10-09 18:20:42 +08:00
|
|
|
nums.insert(3, 6);
|
|
|
|
print('在索引 3 处插入数字 6 ,得到 nums = $nums');
|
2023-02-07 21:24:27 +08:00
|
|
|
|
|
|
|
/* 删除元素 */
|
2023-10-09 18:20:42 +08:00
|
|
|
nums.removeAt(3);
|
|
|
|
print('删除索引 3 处的元素,得到 nums = $nums');
|
2023-02-07 21:24:27 +08:00
|
|
|
|
|
|
|
/* 通过索引遍历列表 */
|
|
|
|
int count = 0;
|
2023-10-09 18:20:42 +08:00
|
|
|
for (var i = 0; i < nums.length; i++) {
|
2023-02-07 21:24:27 +08:00
|
|
|
count++;
|
|
|
|
}
|
|
|
|
/* 直接遍历列表元素 */
|
|
|
|
count = 0;
|
2023-10-09 18:20:42 +08:00
|
|
|
for (var n in nums) {
|
2023-02-07 21:24:27 +08:00
|
|
|
count++;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* 拼接两个列表 */
|
2023-10-09 18:20:42 +08:00
|
|
|
List<int> nums1 = [6, 8, 7, 10, 9];
|
|
|
|
nums.addAll(nums1);
|
|
|
|
print('将列表 nums1 拼接到 nums 之后,得到 nums = $nums');
|
2023-02-07 21:24:27 +08:00
|
|
|
|
|
|
|
/* 排序列表 */
|
2023-10-09 18:20:42 +08:00
|
|
|
nums.sort();
|
|
|
|
print('排序列表后 nums = $nums');
|
2023-05-30 13:00:16 +08:00
|
|
|
}
|