美文网首页
Kotlin语言(七):数据结构

Kotlin语言(七):数据结构

作者: SupKing_a520 | 来源:发表于2022-01-17 15:51 被阅读0次

    1、元组数据

    fun main() {
        /**-------------------- 二元元组 --------------------*/
        val pair = Pair<String, Int>("张三", 20)
        println("(${pair.first}, ${pair.second})")
        //(张三, 20)
    
        val pair2 = "李四" to 25
        println("(${pair2.first}, ${pair2.second})")
        println(pair2.toString())
        //(李四, 25)
    
        /**-------------------- 三元元组 --------------------*/
        val triple = Triple<String, Int, Boolean>("王五", 18, true)
        println("(${triple.first}, ${triple.second}, ${triple.third})")
        println(triple.toString())
        //(王五, 18, true)
    }
    

    2、区间 Range

    fun main() {
        /**-------------------- 1、区间定义 --------------------*/
        val range1: IntRange = 1..10
        val range2: IntRange = IntRange(1, 10)
        val range3: IntRange = 1.rangeTo(10)
    
        val range4: LongRange = 1L..10L
        val range5: LongRange = LongRange(1, 10)
        val range6: LongRange = 1L.rangeTo(10L)
    
        val range7: CharRange = 'a'..'z'
        val range8: CharRange = CharRange('a', 'z')
        val range9: CharRange = 'a'.rangeTo('z')
    
        //until 半开半闭区间
        val range: IntRange = 1 until 100 //[1, 100)
    
    
        /**-------------------- 2、区间遍历 --------------------*/
        for (i in range1) {
            print("$i ")
        }
        println()
        //1 2 3 4 5 6 7 8 9 10
    
        for((index, i) in range1.withIndex()){
            print("($index, $i) ")
        }
        println()
        //(0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 7) (7, 8) (8, 9) (9, 10)
    
        range1.forEach {
            print("$it ")
        }
        println()
        //1 2 3 4 5 6 7 8 9 10
    
        range1.forEachIndexed { index, i ->
            print("($index, $i) ")
        }
        println()
        //(0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 7) (7, 8) (8, 9) (9, 10)
    
    
        /**-------------------- 3、反向区间 --------------------*/
        val range10: IntProgression = 10 downTo 1
        range10.forEach {
            print("$it ")
        }
        println()
        //10 9 8 7 6 5 4 3 2 1
    
        val range11: LongProgression = 10L downTo 1L
        range11.forEach {
            print("$it ")
        }
        println()
        //10 9 8 7 6 5 4 3 2 1
    
        val range12: CharProgression = 'f' downTo 'a'
        range12.forEach {
            print("$it ")
        }
        println()
        //f e d c b a
    
    
        /**-------------------- 4、区间反转 --------------------*/
        val range13 = range1.reversed()
        range13.forEach {
            print("$it ")
        }
        println()
        //10 9 8 7 6 5 4 3 2 1
    
    
        /**-------------------- 5、区间步长 --------------------*/
        val range14 = 1..100 step 10
        val range15 = IntRange(1, 100) step 10
        val range16 = 1.rangeTo(100) step 10
        val range17 = 100 downTo 1 step 10
        val range18 = range1.reversed() step 10
        range14.forEach {
            print("$it ")
        }
        println()
        //1 11 21 31 41 51 61 71 81 91
    
        //for 循环里面也可以使用 step 步长
        for (i in range1 step 2){
            print("$i ")
        }
        println()
        //1 3 5 7 9
    }
    

    3、数组 Array

    fun main() {
        /**-------------------- 1.数组定义 --------------------*/
        //(1)使用 arrayOf 创建
        val arr0: Array<String> = arrayOf("张三", "李四", "王五")
        val arr1: Array<Int> = arrayOf(10, 20, 30)
        val arr2: Array<Char> = arrayOf('a', 'b', 'c')
        val arr3: Array<Any> = arrayOf("张三", 10, 'a')
    
        //(2)使用构造函数创建具体类型和容量的数组
        val intArray = IntArray(4)
        val intArray1 = IntArray(4) { 0 }//数组长度为4并且全部初始化为0
        val booleanArray = BooleanArray(4)
        val byteArray = ByteArray(4)
        val shortArray = ShortArray(4)
        val charArray = CharArray(4)
        val floatArray = FloatArray(4)
        val doubleArray = DoubleArray(4)
        val longArray = LongArray(4)
    
        //注:除八大基本数据类型之外的对象数据类型只能通过 arrayOf 创建,例如 String 数组
    
    
        /**-------------------- 2.数组的遍历 --------------------*/
        for (s in arr0) {
            print("$s ")
        }
        println()
        //张三 李四 王五
    
        for ((index, s) in arr0.withIndex()) {
            print("($index, $s) ")
        }
        println()
        //(0, 张三) (1, 李四) (2, 王五)
    
        arr3.forEach {
            print("$it ")
        }
        println()
    
        //张三 10 a
        arr3.forEachIndexed { index, s ->
            print("($index, $s) ")
        }
        println()
        //(0, 张三) (1, 10) (2, a)
    
    
        /**-------------------- 3.数组元素的获取 --------------------*/
        val temp0 = arr0.get(0)
        val temp1 = arr0[0]
        println("temp0=$temp0 temp1=$temp1")
    
    
        /**-------------------- 4.数组元素的修改 --------------------*/
        arr0[0] = "马六"
        arr0.set(1, "何七")
        arr0.forEach {
            print("$it ")
        }
        println()
        //马六 何七 王五
    
    
        /**-------------------- 5.其他 api --------------------*/
        val array = arrayOf("张三", "李四", "王五", "张三", "李四", "王五")
        //(1)返回第一个匹配元素的角标,如果没有找到则返回-1
        val index11 = array.indexOf("张三")
        val index12 = array.indexOf("马六")
        println("index11=$index11 index12=$index12")
        //index11=0 index12=-1
    
        //(2)返回最后一个匹配元素的角标,如果没有找到则返回-1
        val index21 = array.lastIndexOf("张三")
        val index22 = array.lastIndexOf("马六")
        println("index21=$index21 index22=$index22")
        //index21=3 index22=-1
    
        //(3)返回满足规则的第一个元素的角标,如果没有则返回-1
        val index31 = array.indexOfFirst {
            it.startsWith("张")
        }
        val index32 = array.indexOfFirst {
            it.startsWith("马")
        }
        println("index31=$index31 index32=$index32")
        //index31=0 index32=-1
    
        //(4)返回满足规则的最后一个元素的角标,如果没有则返回-1
        val index41 = array.indexOfLast {
            it.startsWith("张")
        }
        val index42 = array.indexOfLast {
            it.startsWith("马")
        }
        println("index41=$index41 index42=$index42")
        //index41=3 index42=-1
    }
    

    4、枚举 enum

    enum class Week {
        Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
    }
    
    fun todo(week: Week) {
        when (week) {
            in Week.Monday..Week.Friday -> println("上班")
            else -> println("休息")
        }
    }
    
    
    enum class Color(var r: Int, var g: Int, var b: Int) {
        Red(255, 0, 0),
        Green(0, 255, 0),
        Blue(0, 0, 255)
    }
    
    fun main() {
        println(Week.Monday)  // Monday
        // ordinal 枚举常数的序数(它在枚举声明中的位置,初始序数为0)
        Week.values().forEach { println("${it.ordinal} -> $it") }
    
        todo(Week.Wednesday) // 上班
        todo(Week.Sunday)    // 休息
    
    
        println("${Color.Red}[${Color.Red.r}, ${Color.Red.g}, ${Color.Red.b}]")
        // Red[255, 0, 0,]
    }
    

    5、数据类 data

    /**
     * 数据类:
     * 1、使用关键字 data 定义数据类
     * 2、会自动生成 构造函数、get、set、toString、hashCode、equals、copy、component
     */
    data class News(var title: String, var desc: String, var image: String, var content: String)
    
    fun main() {
        val news = News("标题", "描述", "图片", "内容")
        println(news.title)      // 标题
        println(news.desc)       // 描述
        println(news.image)      // 图片
        println(news.content)    // 内容
        println(news.toString()) // News(title=标题, desc=描述, image=图片, content=内容)
        println(news.hashCode()) // 807819163
    
        val newsCopy = news.copy()
        println(newsCopy.toString()) // News(title=标题, desc=描述, image=图片, content=内容)
        val newsCopyChange = news.copy("王者荣耀")
        println(newsCopyChange.toString()) //News(title=王者荣耀, desc=描述, image=图片, content=内容)
    
        println(news == newsCopy)  // true
        println(news === newsCopy) // false
    
        println(news.component1()) // 标题    java: public final String component1() {return this.title;}
        println(news.component2()) // 描述    java: public final String component1() {return this.desc;}
        println(news.component3()) // 图片    java: public final String component1() {return this.image;}
        println(news.component4()) // 内容    java: public final String component1() {return this.content;}
    
        // 解构
        val (title, desc, image, content) = news
        println(title)    // 标题
        println(desc)     // 描述
        println(image)    // 图片
        println(content)  // 内容
    }
    

    6、密封类 sealed

    /**
     * 密封类 sealed:封装的是类型
     */
    sealed class NedStark {
        class RobStark : NedStark()
        class SansaStark : NedStark()
        class AryaStark : NedStark()
        class BrandonStark : NedStark()
    }
    
    class JonSnow : NedStark()
    
    /**
     * 判断有没有继承权
     */
    fun hasRight(stark: NedStark): Boolean {
        return when (stark) {
            is NedStark.RobStark -> true
            is NedStark.SansaStark -> true
            is NedStark.AryaStark -> true
            is NedStark.BrandonStark -> true
            else -> false
        }
    }
    
    fun main() {
        val stark1 = NedStark.RobStark()
        println(hasRight(stark1)) // true
    
        val stark2 = JonSnow()
        println(hasRight(stark2)) // false
    }
    

    7、List 集合

    fun main() {
        // 1、不可变 list
        val list = listOf("毛晓彤", "林青霞", "赵露思", "毛晓彤", "毛晓彤")
        println(list)                                // [毛晓彤, 林青霞, 赵露思, 毛晓彤, 毛晓彤]
        println(list[0])                             // 毛晓彤
        println(list.indexOf("毛晓彤"))               // 0
        println(list.lastIndexOf("毛晓彤"))  // 4
        println(list.first())                        // 毛晓彤
        println(list.last())                         // 毛晓彤
        println(list.contains("赵露思"))              // true
        println(list.subList(1, 3))                  // [林青霞, 赵露思]
        println(list.size)                           // 5
        println(list.lastIndex)                      // 4
        println(list.asReversed())                   // [毛晓彤, 毛晓彤, 赵露思, 林青霞, 毛晓彤]
    
        val list2 = List(4) { index -> index * 2 }
        println(list2)                  // [0, 2, 4, 6]
        println(list2.binarySearch(4))  // 2
    
        // 2、可变 list
        val mutableList = mutableListOf("林青霞", "赵露思", "毛晓彤")
        println(mutableList)       //[林青霞, 赵露思, 毛晓彤]
        mutableList.add("金晨")
        println(mutableList)       //[林青霞, 赵露思, 毛晓彤, 金晨]
        mutableList.forEach { println(it) }
        val mutableList2 = MutableList<Int>(3) { index -> index * index }
        println(mutableList2)      //[0, 1, 4]
    
        // 3、java 中的 list
        val arrList = ArrayList<String>()
        val arrList1 = arrayListOf<String>()
        val linkList = LinkedList<String>()
    }
    

    8、Set 集合

    fun main() {
        // 1.不可变 set
        val set = setOf("A", "B", "A")
        println(set)  // [A, B]
    
        // 2.可变 set
        val mutableSet = mutableSetOf("A", "B", "A")
        println(mutableSet)  // [A, B]
        mutableSet.add("C")
        println(mutableSet)  // [A, B, C]
    
        val hashSet = hashSetOf("A", "B", "A")
        println(hashSet)   //[A, B]
        hashSet.add("C")
        println(hashSet)   //[A, B, C]
    
        val linkSet = linkedSetOf("A", "B", "A")
        println(linkSet)   //[A, B]
        linkSet.add("C")
        println(linkSet)   //[A, B, C]
    
        // 3.相关接口
        println(set.size)
        set.forEach {
            println(it)
        }
        set.contains("A")
        println(set.isEmpty())
        println(set.indexOf("B"))
        println(set.last())
        println(set.first())
        println(set.reversed())
    
        //4.java 中的 set 集合
        val s1 = HashSet<String>()
        val s2 = LinkedHashSet<String>()
        val s3 = TreeSet<String>()
    }
    

    9、Map 集合

    fun main() {
        // 1.不可变 Map
        val map = mapOf("A" to 1, "B" to 2, "C" to 3)
        println(map)         // {A=1, B=2, C=3}
    
        // 2.可变 Map
        val mutableMap = mutableMapOf("A" to 1, "B" to 2, "C" to 3)
        println(mutableMap)  // {A=1, B=2, C=3}
        mutableMap.put("D", 4)
        println(mutableMap)  // {A=1, B=2, C=3, D=4}
    
        val hashMap = hashMapOf("A" to 1, "B" to 2, "C" to 3)
        println(hashMap)     // {A=1, B=2, C=3}
        mutableMap.put("D", 4)
        println(mutableMap)  // {A=1, B=2, C=3, D=4}
    
        val linkedMap = linkedMapOf("A" to 1, "B" to 2, "C" to 3)
        println(linkedMap)   // {A=1, B=2, C=3}
        mutableMap["D"] = 4
        println(mutableMap)  // {A=1, B=2, C=3, D=4}
        mutableMap["A"] = 5
        println(mutableMap)  // {A=5, B=2, C=3, D=4}
    
        // 3.相关接口
        mutableMap["B"] = 11
        println(mutableMap)        // {A=5, B=11, C=3, D=4}
        println(mutableMap["B"])   // 11
        println(mutableMap.keys)   // [A, B, C, D]
        println(mutableMap.values) // [5, 11, 3, 4]
        for ((key, value) in mutableMap) {
            println("{$key = $value}")
        }
        mutableMap.forEach { t, u ->
            println("{$t = $u}")
        }
    
        // 4.java 中的 Map
        val m1 = HashMap<String, Int>()
        val m2 = LinkedHashMap<String, Int>()
        val m3 = TreeMap<String, Int>()
    }
    

    相关文章

      网友评论

          本文标题:Kotlin语言(七):数据结构

          本文链接:https://www.haomeiwen.com/subject/ibmchrtx.html