|
|
@ -129,7 +129,12 @@
|
|
|
|
=== "Kotlin"
|
|
|
|
=== "Kotlin"
|
|
|
|
|
|
|
|
|
|
|
|
```kotlin title="list.kt"
|
|
|
|
```kotlin title="list.kt"
|
|
|
|
|
|
|
|
/* 初始化列表 */
|
|
|
|
|
|
|
|
// 无初始值
|
|
|
|
|
|
|
|
var nums1 = listOf<Int>()
|
|
|
|
|
|
|
|
// 有初始值
|
|
|
|
|
|
|
|
var numbers = arrayOf(1, 3, 2, 5, 4)
|
|
|
|
|
|
|
|
var nums = numbers.toMutableList()
|
|
|
|
```
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
=== "Zig"
|
|
|
|
=== "Zig"
|
|
|
@ -257,7 +262,10 @@
|
|
|
|
=== "Kotlin"
|
|
|
|
=== "Kotlin"
|
|
|
|
|
|
|
|
|
|
|
|
```kotlin title="list.kt"
|
|
|
|
```kotlin title="list.kt"
|
|
|
|
|
|
|
|
/* 访问元素 */
|
|
|
|
|
|
|
|
val num = nums[1] // 访问索引 1 处的元素
|
|
|
|
|
|
|
|
/* 更新元素 */
|
|
|
|
|
|
|
|
nums[1] = 0 // 将索引 1 处的元素更新为 0
|
|
|
|
```
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
=== "Zig"
|
|
|
|
=== "Zig"
|
|
|
@ -487,7 +495,21 @@
|
|
|
|
=== "Kotlin"
|
|
|
|
=== "Kotlin"
|
|
|
|
|
|
|
|
|
|
|
|
```kotlin title="list.kt"
|
|
|
|
```kotlin title="list.kt"
|
|
|
|
|
|
|
|
/* 清空列表 */
|
|
|
|
|
|
|
|
nums.clear();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/* 在尾部添加元素 */
|
|
|
|
|
|
|
|
nums.add(1);
|
|
|
|
|
|
|
|
nums.add(3);
|
|
|
|
|
|
|
|
nums.add(2);
|
|
|
|
|
|
|
|
nums.add(5);
|
|
|
|
|
|
|
|
nums.add(4);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/* 在中间插入元素 */
|
|
|
|
|
|
|
|
nums.add(3, 6); // 在索引 3 处插入数字 6
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/* 删除元素 */
|
|
|
|
|
|
|
|
nums.remove(3); // 删除索引 3 处的元素
|
|
|
|
```
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
=== "Zig"
|
|
|
|
=== "Zig"
|
|
|
@ -683,7 +705,16 @@
|
|
|
|
=== "Kotlin"
|
|
|
|
=== "Kotlin"
|
|
|
|
|
|
|
|
|
|
|
|
```kotlin title="list.kt"
|
|
|
|
```kotlin title="list.kt"
|
|
|
|
|
|
|
|
/* 通过索引遍历列表 */
|
|
|
|
|
|
|
|
var count = 0
|
|
|
|
|
|
|
|
for (i in nums.indices) {
|
|
|
|
|
|
|
|
count += nums[i]
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/* 直接遍历列表元素 */
|
|
|
|
|
|
|
|
for (num in nums) {
|
|
|
|
|
|
|
|
count += num
|
|
|
|
|
|
|
|
}
|
|
|
|
```
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
=== "Zig"
|
|
|
|
=== "Zig"
|
|
|
@ -801,7 +832,9 @@
|
|
|
|
=== "Kotlin"
|
|
|
|
=== "Kotlin"
|
|
|
|
|
|
|
|
|
|
|
|
```kotlin title="list.kt"
|
|
|
|
```kotlin title="list.kt"
|
|
|
|
|
|
|
|
/* 拼接两个列表 */
|
|
|
|
|
|
|
|
val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList()
|
|
|
|
|
|
|
|
nums.addAll(nums1) // 将列表 nums1 拼接到 nums 之后
|
|
|
|
```
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
=== "Zig"
|
|
|
|
=== "Zig"
|
|
|
@ -901,7 +934,8 @@
|
|
|
|
=== "Kotlin"
|
|
|
|
=== "Kotlin"
|
|
|
|
|
|
|
|
|
|
|
|
```kotlin title="list.kt"
|
|
|
|
```kotlin title="list.kt"
|
|
|
|
|
|
|
|
/* 排序列表 */
|
|
|
|
|
|
|
|
nums.sort() // 排序后,列表元素从小到大排列
|
|
|
|
```
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
=== "Zig"
|
|
|
|
=== "Zig"
|
|
|
|