如何仅通过提供大小在 Kotlin 中像在 Java 中一样创建数组? [英] How can I create an array in Kotlin like in Java by just providing a size?

查看:25
本文介绍了如何仅通过提供大小在 Kotlin 中像在 Java 中一样创建数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何像在 java 中那样创建数组?

How can I create a Array like we do in java?

int A[] = new int[N];

我怎样才能在 Kotlin 中做到这一点?

How can I do this in Kotlin?

推荐答案

根据 reference,数组的创建方式如下:

According to the reference, arrays are created in the following way:

  • 对于 Java 的原始类型,有不同的类型 IntArrayDoubleArray 等,它们存储 未装箱值.

  • For Java's primitive types there are distinct types IntArray, DoubleArray etc. which store unboxed values.

它们是用相应的构造函数和工厂函数创建的:

They are created with the corresponding constructors and factory functions:

val arrayOfZeros = IntArray(size) //equivalent in Java: new int[size]
val numbersFromOne = IntArray(size) { it + 1 }
val myInts = intArrayOf(1, 1, 2, 3, 5, 8, 13, 21)

第一个和 Java 中的类似,它只是创建一个用默认值填充的原始数组,例如Int 为零,false 表示 Boolean.

The first one is simillar to that in Java, it just creates a primitive array filled with the default value, e.g. zero for Int, false for Boolean.

非原始数组由 Array 类表示,其中 T 是项目类型.

Non primitive-arrays are represented by Array<T> class, where T is the items type.

T 仍然可以是 Java 中的基本类型之一(Int, Boolean,...),但里面的值将是等效于 Java 的 IntegerDouble 等.

T can still be one of types primitive in Java (Int, Boolean,...), but the values inside will be boxed equivalently to Java's Integer, Double and so on.

此外,T 可以是 可为空和非空 类似于 StringString?.

Also, T can be both nullable and non-null like String and String?.

它们的创建方式类似:

val nulls = arrayOfNulls<String>(size) //equivalent in Java: new String[size]
val strings = Array(size) { "n = $it" } 
val myStrings = arrayOf("foo", "bar", "baz")

val boxedInts = arrayOfNulls<Int>(size) //equivalent in Java: new Integer[size]
val boxedZeros = Array(size) { 0 }

这篇关于如何仅通过提供大小在 Kotlin 中像在 Java 中一样创建数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆