您好,登錄后才能下訂單哦!
Kotlin中的數組容器有哪些?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
Arrays
Kotlin 標準庫提供了arrayOf()創建數組, **ArrayOf創建特定類型數組
val array = arrayOf(1, 2, 3) val countries = arrayOf("UK", "Germany", "Italy") val numbers = intArrayOf(10, 20, 30) val array1 = Array(10, { k -> k * k }) val longArray = emptyArray<Long>() val studentArray = Array<Student>(2) studentArray[0] = Student("james")
和Java不一樣,Kotlin 的數組是容器類, 提供了 ByteArray, CharArray, ShortArray, IntArray, LongArray, BooleanArray, FloatArray, and DoubleArray。
Lists
List是有序容器,Kotlin 標準庫通過listOf()創建list
val intList: List<Int> = listOf(20, 5, 10) val emptyList: List<String> = emptyList<String>() val nonNulls: List<String> = listOfNotNull<String>(null, "a", "b", "c") val doubleList: ArrayList<Double> = arrayListOf(84.88, 100.25, 999.99)
其中,intList, emptyList, nonNulls是只讀的實例,要修改這些list,需要進行類型轉換
(intList as AbstractList<Int>).set(0, 30) (nonNulls as java.util.ArrayList).addAll(arrayOf("x", "y"))
Maps
Map是<key, value>容器, Kotlin提供mapOf創建map
val map = mapOf("a" to 1, "b" to 2, "c" to 3) val value = map.get(b) val states: MutableMap<String, String>= mutableMapOf("AL" to "Alabama", "AK" to "Alaska", "AZ" to "Arizona") val customers: java.util.HashMap<Int, Customer> = hashMapOf(1 to Customer("Dina", "Kreps", 1), 2 to Customer("Andy", "Smith", 2)) val linkedHashMap: java.util.LinkedHashMap<String, String> = linkedMapOf("red" to "#FF0000","azure" to "#F0FFFF","white" to "#FFFFFF") val sortedMap: java.util.SortedMap<Int, String> = sortedMapOf(4 to "d", 1 to "a", 3 to "c", 2 to "b")
Sets
Set是沒有重復項的容器, Kotlin提供setOf創建Set
val intSet: Set<Int> = setOf(1, 21, 21, 2, 6, 3, 2) //1,21,2,6,3 val hashSet: java.util.HashSet<Book> = hashSetOf( Book("Jules Verne", "Around the World in 80 Days Paperback", 2014, "978-1503215153"), Book("Jules Verne", "Around the World in 80 Days Paperback", 2014, "978-1503215153")) val sortedIntegers: java.util.TreeSet<Int> = sortedSetOf(11, 0, 9, 11, 9, 8)
看完上述內容,你們掌握Kotlin中的數組容器有哪些的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。