arrays - 使用 kotlin 如何将数组附加到二维数组
问题描述
我想获取坐标并将它们添加到我想从函数返回的数组中,但我不知道如何在 kotlin 中附加到带有另一个数组的空数组
var temp:Array<Array<Int>> = arrayOf<Array<Int>>()
var i:Int = 0
while (true){
// if you see another of the same type then break
if(currentPlayer == 1){
if(ystart-i < 0){ // if you would go out of bounds on the next it and the current one does not have an opposite then breakwith temp as nothing
temp = arrayOf<Array<Int>>()
break
}else if(touchnum[ystart-i][xstart] == 1){
break
}else{
val slice: IntArray = intArrayOf(xstart, ystart-i)
temp.plusElement(slice)
}
}else{
}
解决方案
数组在 JVM 上是固定长度的。一旦创建,您就无法更改它们的长度。动态增长数组的等效概念称为列表。
在 Kotlin 中,它们由MutableList接口表示(或者List
当您需要只读引用时)。MutableList
您可以使用该函数创建一个实例mutableListOf<T>()
(其中T
是列表中元素的类型)。然后使用 . 添加元素list.add(element)
。
那是你的“主要”名单。现在让我们谈谈您放入其中的元素。
在 Kotlin 中,将元组(如坐标)表示为数组并不是很习惯。对于 2D 坐标,已经有一个名为Pair<A, B>的类型。但老实说,自己编写一个特定于领域的类非常便宜,我鼓励你创建自己的类,例如:
data class Point2D(val x: Int, val y: Int)
然后您可以将此类的实例添加到您的列表中:
list.add(Point2D(xstart, ystart-i))
推荐阅读
- json - 从 Hyper 获取请求,解析 JSON,并将其转换为 rust 中的结构
- javascript - Javascript数组被覆盖?
- python - 有没有更紧凑的方法可以使用 for 循环附加到列表?
- excel - 用于从包含在特定文件夹中的工作簿中导入工作表的 VBA 代码
- javascript - 使用 javascript 附加到引导表
- haskell - 避免在 GHCI 中出现不适当的非详尽模式匹配警告
- network-programming - 在 CodenameOne 中,ConnectionRequest.setTimeout 的参数是毫秒还是秒?
- python - Flask 和 Python,尝试从表单读取时不允许使用方法
- java - 从 csv 文件设置父 ID
- ios - 如何在 Swift 4.2 中编写键盘通知?