// Array of integers of a size of N
val arr = IntArray(N)
// Array of integers of a size of N initialized with a default value of 2
val arr = IntArray(N) { i -> 2 }
var arr = IntArray(size) // construct with only size
然后从用户或其他集合或任何你想要的地方获取初始值。
var arr = IntArray(size){0} // construct with size and fill array with 0
var arr = IntArray(size){it} // construct with size and fill with its index
我们也可以用内置函数创建数组,比如-
var arr = intArrayOf(1, 2, 3, 4, 5) // create an array with 5 values
另一种方式
var arr = Array(size){0} // it will create an integer array
var arr = Array<String>(size){"$it"} // this will create array with "0", "1", "2" and so on.
我认为有一件事是值得一提的,从文档中不太直观的是,当你使用工厂函数创建一个数组并指定它的大小时,数组的初始化值等于它们的下标值。例如,在这样的数组中:
val array = Array(5, { i -> i }),赋值的初始值是[0,1,2,3,4]而不是[0,0,0,0,0]。这就是为什么从文档中,val asc = Array(5, { i -> (i * i).toString() })产生了["0", "1", "4", "9", "16"]的答案
val iconsArr : IntArray = resources.getIntArray(R.array.navigation_drawer_items_icon)
val names : Array<String> = resources.getStringArray(R.array.navigation_drawer_items_name)
// Use lambda function to add data in my custom model class i.e. DrawerItem
val drawerItems = Array<DrawerItem>(iconsArr.size, init =
{ index -> DrawerItem(iconsArr[index], names[index])})
Log.d(LOGGER_TAG, "Number of items in drawer is: "+ drawerItems.size)
自定义模型类-
class DrawerItem(var icon: Int, var name: String) {
}
/**
* An array of ints. When targeting the JVM, instances of this class are
* represented as `int[]`.
* @constructor Creates a new array of the specified [size], with all elements
* initialized to zero.
*/
public class IntArray(size: Int) {
/**
* Creates a new array of the specified [size], where each element is
* calculated by calling the specified
* [init] function. The [init] function returns an array element given
* its index.
*/
public inline constructor(size: Int, init: (Int) -> Int)
...
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//create your int array here
numbers= intArrayOf(10,20,30,40,50)
}
/**
* Creates a new array of the specified [size], where each element is calculated by calling the specified
* [init] function. The [init] function returns an array element given its index.
*/
public inline constructor(size: Int, init: (Int) -> Int)
var Arr1 = arrayOf(1,10,4,6,15)
var Arr2 = arrayOf<Int>(1,10,4,6,15)
var Arr3 = arrayOf<String>("Surat","Mumbai","Rajkot")
var Arr4 = arrayOf(1,10,4, "Ajay","Prakesh")
var Arr5: IntArray = intArrayOf(5,10,15,20)
private fun populateArray(): Array<Item> {
val mutableArray = ArrayList<Item>()
for (i in 1..10_000) {
mutableArray.add(Item("Item Number $i" ))
}
return mutableArray.toTypedArray()
}