簡體   English   中英

Kotlin 中的二維數組

[英]2D Array in Kotlin

你如何在 Kotlin 中創建一個 2D Int 數組? 我正在嘗試將此代碼轉換為 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);

這是我嘗試過的一次嘗試,其中第一個二維數組不起作用,但我讓一維數組起作用:

//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);

您可以將這行代碼用於整數數組。

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

這行代碼非常簡單,像一維數組一樣工作,也可以像 Java 二維數組一樣訪問。

您正試圖將您的 IntArrays 放入另一個數組中以使其成為二維數組。 該數組的類型不能是 intArray,這就是失敗的原因。 arrayOf而不是intArrayOf包裹你的初始數組。

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

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

簡答:

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

這是另一個示例,其中包含有關正在發生的事情的更多詳細信息:

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

第一個參數是大小,第二個 lambda 方法用於初始化。

創建矩陣時我一直在使用這個單線

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

1. 嵌套的arrayOf調用

您可以嵌套對arrayOf調用,例如,要創建一個IntArray數組,請執行以下操作:

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

請注意, IntArray本身僅將Int類型的參數作為參數,因此您不能擁有IntArray<IntArray> ,這顯然沒有多大意義。

2. 使用Array::constructor(size: Int, init: (Int) -> T)進行重復邏輯

如果要根據索引創建具有某些邏輯行為的內部數組,可以使用帶有大小和 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]]

您似乎正在嘗試在 Kotlin 中創建一個ColorStateList 代碼有點亂,我會盡量保持可讀性:

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)
)

為此,您可以使用簡單的一維(線性)陣列。 例如,這是我的 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)")
        }
    }
}

使用內聯函數和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")

  ... 

您可以在 kotlin 中創建二維數組。

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

這是一個 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()
    }


}

它是這樣工作的:

在此處輸入圖片說明

您可以創建兩個一維數組並將它們添加到新數組中。

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