简体   繁体   English

Kotlin 中的二维数组

[英]2D Array in Kotlin

How do you make a 2D Int array in Kotlin?你如何在 Kotlin 中创建一个 2D Int 数组? I'm trying to convert this code to Kotlin:我正在尝试将此代码转换为 Kotlin:

int[][] states = new int[][] {
      new int[]{-android.R.attr.state_pressed}, // not pressed
      new int[] { android.R.attr.state_pressed}  // pressed
};
int[] colors = new int[] {
      foregroundColor,
      accentColor,
      accentColor
};
ColorStateList myList = new ColorStateList(states, colors);

Here is one attempt I tried, where the first 2D array didn't work, but I got the 1D array to work:这是我尝试过的一次尝试,其中第一个二维数组不起作用,但我让一维数组起作用:

//This doesn't work:
var states: IntArray = intArrayOf(
    intArrayOf(-android.R.attr.state_pressed), // not pressed
    intArrayOf(android.R.attr.state_pressed)  // pressed
);
//This array works:
var colors: IntArray = intArrayOf(
    foregroundColor,
    accentColor,
    accentColor
);
val myList: ColorStateList = ColorStateList(states, colors);

You may use this line of code for an Integer array.您可以将这行代码用于整数数组。

val array = Array(row) { IntArray(column) }

This line of code is pretty simple and works like 1D array and also can be accessible like java 2D array.这行代码非常简单,像一维数组一样工作,也可以像 Java 二维数组一样访问。

You are trying to put your IntArrays inside another array to make it 2-dimensional.您正试图将您的 IntArrays 放入另一个数组中以使其成为二维数组。 The type of that array cannot be intArray, which is why this fails.该数组的类型不能是 intArray,这就是失败的原因。 Wrap your initial arrays with arrayOf instead of intArrayOf .arrayOf而不是intArrayOf包裹你的初始数组。

val even: IntArray = intArrayOf(2, 4, 6)
val odd: IntArray = intArrayOf(1, 3, 5)

val lala: Array<IntArray> = arrayOf(even, odd)

Short Answer:简答:

// A 6x5 array of Int, all set to 0.
var m = Array(6) {Array(5) {0} }

Here is another example with more details on what is going on:这是另一个示例,其中包含有关正在发生的事情的更多详细信息:

// a 6x5 Int array initialise all to 0
var m = Array(6, {i -> Array(5, {j -> 0})})

The first parameter is the size, the second lambda method is for initialisation.第一个参数是大小,第二个 lambda 方法用于初始化。

创建矩阵时我一直在使用这个单线

var matrix: Array<IntArray> = Array(height) { IntArray(width) }

1. Nested arrayOf calls 1. 嵌套的arrayOf调用

You can nest calls of arrayOf , eg, to create an Array of IntArray , do the following:您可以嵌套对arrayOf调用,例如,要创建一个IntArray数组,请执行以下操作:

val first: Array<IntArray> = arrayOf(
    intArrayOf(2, 4, 6),
    intArrayOf(1, 3, 5)
)

Note that the IntArray itself only takes arguments of type Int as arguments, so you cannot have an IntArray<IntArray> which obviously does not make much sense anyway.请注意, IntArray本身仅将Int类型的参数作为参数,因此您不能拥有IntArray<IntArray> ,这显然没有多大意义。

2. Use Array::constructor(size: Int, init: (Int) -> T) for repeated logic 2. 使用Array::constructor(size: Int, init: (Int) -> T)进行重复逻辑

If you want to create your inner arrays with some logical behaviour based on the index, you can make use of the Array constructor taking a size and an init block:如果要根据索引创建具有某些逻辑行为的内部数组,可以使用带有大小和 init 块的Array构造函数:

val second: Array<IntArray> = Array(3) {
    intArrayOf(it * 1, it * 2, it * 3, it * 4)
} 
//[[0, 0, 0, 0], [1, 2, 3, 4], [2, 4, 6, 8]]

It seems that you are trying to create a ColorStateList in Kotlin.您似乎正在尝试在 Kotlin 中创建一个ColorStateList The code for that is a bit messy, i'll try to keep it readable:代码有点乱,我会尽量保持可读性:

val resolvedColor = Color.rgb(214, 0, 0)
val states = arrayOf(
    intArrayOf(-android.R.attr.state_pressed),
    intArrayOf(android.R.attr.state_pressed)
)

val csl = ColorStateList(
    states,
    intArrayOf(resolvedColor, Color.WHITE)
)

You can use a simple 1D (linear) array for this purpose.为此,您可以使用简单的一维(线性)阵列。 For example, this is my class for a rectangle array of Double values:例如,这是我的 Double 值矩形数组类:

/**
 * Rect array of Double values
 */
class DoubleRectArray(private val rows: Int, private val cols: Int) {
    private val innerArray: DoubleArray

    init {
        if(rows < 1) {
            throw IllegalArgumentException("Rows value is invalid. It must be greater than 0")
        }

        if(cols < 1) {
            throw IllegalArgumentException("Cols value is invalid. It must be greater than 0")
        }

        innerArray = DoubleArray(rows*cols)
    }

    /**
     *
     */
    fun get(row: Int, col: Int): Double {
        checkRowAndCol(row, col)
        return innerArray[row*cols + col]
    }

    /**
     *
     */
    fun set(row: Int, col: Int, value: Double) {
        checkRowAndCol(row, col)
        innerArray[row*cols + col] = value
    }

    /**
     *
     */
    private fun checkRowAndCol(row: Int, col: Int) {
        if(row !in 0 until rows) {
            throw ArrayIndexOutOfBoundsException("Row value is invalid. It must be in a 0..${rows-1} interval (inclusive)")
        }

        if(col !in 0 until cols) {
            throw ArrayIndexOutOfBoundsException("Col value is invalid. It must be in a 0..${cols-1} interval (inclusive)")
        }
    }
}

Using an inline function and a Pair :使用内联函数和Pair

  inline fun<reified T> Pair<Int,Int>.createArray(initialValue:T) = Array(this.first){ Array(this.second){initialValue}}

  // Create m*n Array of Ints filled with 0
  val twoDimArray = Pair(10,20).createArray(0)

  // Create m*n Array of Doubles filled with 0.0
  val twoDimArray = Pair(10,20).createArray(0.0)

  // Create m*n Array of Strings filled with "Value"
  val twoDimArray = Pair(10,20).createArray("Value")

  ... 

You can create 2D array in kotlin.您可以在 kotlin 中创建二维数组。

            var twoDarray = Array(8) { IntArray(8) }

this is a example of int 2D array这是一个 int 二维数组的例子

package helloWorld

import java.util.Scanner

fun main(){
    val sc = Scanner(System.`in`)
    print("ENTER THE SIZE OF THE ROW: ")
    var row = sc.nextInt()
    println()
    print("ENTER THE SIZE OF COLUMN: ")
    val column = sc.nextInt()
    println()
    var a = Array(row){IntArray(column)}
    for(i in 0 until row){
        when (i) {
            0 -> {
                println("----------${i+1} st ROW'S DATA----------")
            }
            1 -> {
                println("----------${i+1} nd ROW'S DATA----------")
            }
            2 -> {
                println("----------${i+1} rd ROW'S DATA----------")
            }
            else -> {
                println("----------${i+1} th ROW'S DATA----------")
            }
        }
        for(j in 0 until column)
        {
            print("ENTER ${j+1} COLUMN'S DATA: ")
            var data:Int = sc.nextInt()
            a[i][j]=data;
        }
        println()
    }
    println("COLLECTION OF DATA IS COMPLETED")
    for(i in 0 until row){
        for(j in 0 until column){
            print(a[i][j])
            print(" ")
        }
        println()
    }


}

It works like this:它是这样工作的:

在此处输入图片说明

You can create two one dimensional array and add them in new array.您可以创建两个一维数组并将它们添加到新数组中。

val unChecked = intArrayOf(-android.R.attr.state_checked)
val checked = intArrayOf(android.R.attr.state_checked)
val states = arrayOf(unChecked, checked)

val thumbColors = intArrayOf(Color.WHITE, Color.parseColor("#55FFD4"))
val stateList = ColorStateList(states, thumbColors)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM