首页 > 解决方案 > 使用 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{

                    }

标签: arrayskotlin

解决方案


数组在 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))

推荐阅读