前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Kotlin学习日志(二)数据类型

Kotlin学习日志(二)数据类型

作者头像
晨曦_LLW
发布2020-09-25 14:10:20
3.3K0
发布2020-09-25 14:10:20
举报

一、基本数据类型

Kotlin的基本数据类型和其他高级语言得分类一样,包括整型、长整型、浮点型、双精度、布尔类型、字符型、字符串这几种常见类型,这样说可能过于抽象,那就和java中的基础数据类型来对比一下吧。

基本数据类型名称

Kotlin的数据类型

Java的数据类型

整型

Int

int 和 Integer

长整型

Long

long 和 Long

浮点型

Float

float 和 Float

双精度

Double

double 和 Double

布尔类型

Boolean

boolean 和 Boolean

字符型

Char

char

字符串

String

String

这样就很立体了吧,请注意小写和大写的区别,Java中严格区分大小写的。

1.1变量声明

接下来声明一个变量了, Java的写法如下:

int i = 0;

Kotlin的写法如下:

var i:Int = 0

解释:上面的 var 表示后面是一个变量声明语句,后面是“变量名:变量类型”的格式声明,不同于Java中常见的“变量类型:变量名”这种格式,(PS:这个在刚开始接触Kotlin的时候很容易搞混,用久了就可以了),后面是没有分号的,Java则有,在Kotlin中如果你后面还有其他语句的话则要加上分号,如果无其他语句则回车换行就行,不需要加分号,如下图所示:

在这里插入图片描述
在这里插入图片描述

1.2变量转换

Kotlin中进行数据转换和Java中不同,就不一一对比了,直接说Kotlin中如何进行数据类型转换,Kotlin中都是使用类型转换函数来进行数据类型转换的,让我们来认识一下,如下表

Kotlin的数据类型转换函数

转换函数说明

toInt

转换为整型

toLong

转换为长整型

toFloat

转换为浮点数

toDouble

转换为双精度数

toChar

转换为字符

toString

转换为字符串

接下来我们用代码来演示一下:

修改一下布局文件如下 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_marginTop="20dp"
        android:id="@+id/tv_data"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:layout_marginTop="20dp"
        android:id="@+id/btn_toInt"
        android:text="转换为整型"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <Button
        android:layout_marginTop="20dp"
        android:id="@+id/btn_toLong"
        android:text="转换为长整型"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <Button
        android:layout_marginTop="20dp"
        android:id="@+id/btn_toDouble"
        android:text="转换为双精度数"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <Button
        android:layout_marginTop="20dp"
        android:id="@+id/btn_toChar"
        android:text="转换为字符"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    
</LinearLayout>

然后是MainActivity.kt代码

package com.llw.kotlinstart

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val data:Float = 65.0f
        tv_data.text = data.toString()

        //转整数型
        btn_toInt.setOnClickListener {
            var dataInt:Int = data.toInt()
            tv_data.text = dataInt.toString()
        }
        //转长整数型
        btn_toLong.setOnClickListener {
            var dataLong:Long = data.toLong()
            tv_data.text = dataLong.toString()
        }
        //转双精度数
        btn_toDouble.setOnClickListener {
            var dataDouble:Double = data.toDouble()
            tv_data.text = dataDouble.toString()
        }
        //转字符
        btn_toChar.setOnClickListener {
            var dataChar:Char = data.toChar()
            tv_data.text = dataChar.toString()
        }
    }
}

上面的代码是比较好理解的,一开始我们定义了一个val data:Float 这里的val相当于Java的final,然后赋值给TextView显示出来,接下来点击Button按钮来转换data的值,不同的按钮对应不同的值。

二、数组

说到数组,我们首先看一下Java中的声明数组并初始化

int[] int_array = new int[] {1,2,3};

然后是Kotlin中声明数组并初始化

var int_array:IntArray = intArrayOf(1,2,3)

两者对比,对于同一整型数组的声明,KotlinJava之间有以下区别: (1) Kotlin另外提供了新的整型数组类型,即IntArray。 (2) 分配一个常量数组,Kotlin调用的是 intArrayOf 方法,并不使用new关键字

下面用一个表格来详细说明Kotlin的数组类型及初始化方法

Kotlin的基本数组类型

数据类型的名称

数组类型的初始化方法

整型数组

IntArray

intArrayOf

长整型数组

LongArray

longArrayOf

浮点数组

FloatArray

floatArrayOf

双精度数组

DoubleArray

doubleArrayOf

布尔类型数组

BooleanArray

booleanArrayOf

字符型数组

CharArray

charArrayOf

下面是这些基本类型数组的初始化例子:

var int_array:IntArray = intArrayOf(1,2,3)
        
        var long_array:LongArray = longArrayOf(1,2,3)
        
        var float_array:FloatArray = floatArrayOf(1.0f,2.0f,3.0f)
        
        var double_array:DoubleArray = doubleArrayOf(1.0,2.0,3.0)
        
        var boolean_array:BooleanArray = booleanArrayOf(false,true,false)
        
        var char_array:CharArray = charArrayOf('A','B','C')

我们是不是少了一个数据类型呢,对了就是字符串数组,这个和在Java中是不一样的,Kotlin中不存在名为StringArray的数组类型,因为String是一种特殊的基本数据类型,要想在Kotlin中声明字符串数组,得使用Array<String>类型,同时,分配字符串数组的方法也变成了arrayOf,下面是Kotlin中声明字符串数组的代码示例

var string_array:Array<String> = arrayOf("One","Two","Three")

这个方式就和Java的代码比较相像了,既然字符串数组可以这样写,那个其他的数据类型同样可以这么写,如下所示:

var int_array:Array<Int> = arrayOf(1,2,3)

        var long_array:Array<Long> = arrayOf(1,2,3)

        var float_array:Array<Float> = arrayOf(1.0f,2.0f,3.0f)

        var double_array:Array<Double> = arrayOf(1.0,2.0,3.0)

        var boolean_array:Array<Boolean> = arrayOf(false,true,false)

        var char_array:Array<Char> = arrayOf('A','B','C')

了解了数组的声明与初始化,接下来就是操作这个数组了,

2.1数组元素的操作

对于数组的操作,常见的处理包括获取数组的长度、获取指定位置的数组元素,这些操作在Kotlin与Java中是有区别的,如下: (1)获取数组长度,Java使用**.length**,Kotlin使用**.size**(PS:前面有一个点) (2)获取指定位置的数组元素,Java通过方括号加下标来获取,比如“ string_array[2]”(PS:获取该数组的第三个元素,下标是从0开始的),Kotlin也能通过方括号加下标来获取指定元素,不过Kotlin还有getset两个方法,通过get方法获取元素值,通过set方法修改元素值,我们演示一下,代码如下: 布局文件 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_marginTop="20dp"
        android:id="@+id/tv_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:layout_marginTop="20dp"
        android:id="@+id/btn_string"
        android:text="测试"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    

</LinearLayout>

MainActivity.kt

package com.llw.kotlinstart

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //声明字符串数组
        var string_array:Array<String> = arrayOf("Day","Day","Up")
        btn_string.setOnClickListener {
            var str:String = ""
            var i:Int = 0

            while (i<string_array.size){
                //数组元素通过下标访问
//                str = str + string_array[i] + ","

                //数组元素通过get方法访问
                str = str + string_array.get(i) + ","
                i++

            }
            tv_item.text = str
        }
        
    }
}

运行效果图如下

在这里插入图片描述
在这里插入图片描述

代码也比较简单,说明一下,先声明一个字符串数组,在点击按钮的代码中,声明一个String变量,一个Int变量,并初始化,然后使用while循环,判断String数组的长度大于变量 i,当条件不满足时跳出循环,并显示最终结果在TextView上,循环中的逻辑也比较简单,取出i对应的数组元素,赋值给str,并用逗号隔开,取出的方式可以自选其一,这里就不过多的赘述了,赋值完成之后,i++,这是i就变成1,然后取数组中第二个值,再加一,变成2,取第三个值,再加一,变成3,3>3?,条件不满足,跳出循环,此时就将数组中的值都取出来了,(PS:我相信有基础的人会觉得我很啰嗦,但是这是必要的,后面会精简的),数组的操作就是这样了。

三、字符串

3.1字符串与基本类型的转换

这里我们对比一下Java的转换方式,如下表:

字符串转换目标

Kotlin的转换方式

Java的转换方式

字符串转整型

字符串变量的toInt方法

Integer.parseInt(字符串变量)

字符串转长整型

字符串变量的toLong方法

Long.parseInt(字符串变量)

字符串转浮点数

字符串变量的toFloat方法

Float.parseInt(字符串变量)

字符串转双精度数

字符串变量的toDouble方法

Double.parseInt(字符串变量)

字符串转布尔类型

字符串变量的toBoolean方法

Boolean.parseInt(字符串变量)

字符串转字符数组

字符串变量的toCharArray方法

字符串变量的toCharArray方法

可以看到Kotlin相对于Java的转换要简单一些,通过方法即可实现。

3.2字符串的常用方法

常用方法:查找子串、替换子串、截取指定位置的子串、按特定字符分隔子串等,在这方面Kotlin基本兼容Java的相关方法, 1.查找子串,都调用indexOf方法。 2.截取指定位置子串,都调用substring方法。 3.替换子串,都调用replace方法。 4.按特定字符分隔子串,都调用split方法

下面是查找和截取的使用示例:

布局文件代码 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:textColor="#000"
            android:text="初始值:"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:textColor="#000"
            android:text="200.56"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv_data"/>
    </LinearLayout>

    <LinearLayout
        android:visibility="gone"
        android:id="@+id/result_lay"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:textColor="#000"
            android:text="结果值:"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:textColor="#000"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv_result"/>
    </LinearLayout>

    <Button
        android:layout_marginTop="20dp"
        android:id="@+id/btn_substring"
        android:text="截取字符串"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

MainActivity.kt

package com.llw.kotlinstart

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        


        //截取小数点之前的字符串
        //1.获取要截取的字符串
        var data:String = tv_data.text.toString()
        //2.声明一个结果值
        var result:String = data
        btn_substring.setOnClickListener {
            //查找目标字符,
            if(result.indexOf('.') > 0){
                //如果有,则截取,substring有两个参数,
                // 分别是startIndex开始位置和endIndex结束位置,从第一个字节开始,到小数点停止,之间的内容
                result = result.substring(0,result.indexOf('.'))
                //结果赋值
                tv_result.text = result
                //控件显示  一开始我隐藏了,所以这个时候显示
                result_lay.visibility = View.VISIBLE
            }
        }

        
    }
}

运行效果图如下:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

代码的解释我都已经写好了,一目了然。

接下来是替换字符串,使用replace方法,如下所示: 我们在布局文件activity_main.xml文件中添加如下代码

<LinearLayout
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:textColor="#000"
            android:text="初始值:"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:textColor="#000"
            android:text="abcabcabcabcabcabc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv_replace_data"/>
    </LinearLayout>

    <LinearLayout
        android:visibility="gone"
        android:id="@+id/replace_result_lay"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:textColor="#000"
            android:text="结果值:"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:textColor="#000"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv_replace_result"/>
    </LinearLayout>

    <Button
        android:layout_marginTop="20dp"
        android:id="@+id/btn_replace"
        android:text="替换字符串"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

在MainActivity.kt中新增如下代码:

//替换字符串
        var replaceData:String = tv_replace_data.text.toString()
        btn_replace.setOnClickListener {
            if(replaceData.indexOf('c') > 0){
                //replace方法也有两个参数,oldChar 要替换的目标字符,newChar替换后的字符,我们把c替换成a
                tv_replace_result.text = replaceData.replace('c','a')
                replace_result_lay.visibility = View.VISIBLE
            }
        }

运行效果如下图所示:

在这里插入图片描述
在这里插入图片描述

最后我们再写上截取字符串的示例代码

activity_main.xml文件中再加上如下代码

<LinearLayout
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:textColor="#000"
            android:text="初始值:"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:textColor="#000"
            android:text="abc_def_ghi_jkl_mno_pqr"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv_split_data"/>
    </LinearLayout>

    <LinearLayout
        android:visibility="gone"
        android:id="@+id/split_result_lay"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:textColor="#000"
            android:text="结果值:"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:textColor="#000"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv_split_result"/>
    </LinearLayout>

    <Button
        android:layout_marginTop="20dp"
        android:id="@+id/btn_split"
        android:text="替换字符串"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

MainActivity.kt里面中新增如下代码:

//截取字符串
        var splitData:String = tv_split_data.text.toString()
        btn_split.setOnClickListener {
            if(splitData.indexOf('_') > 0){
                // split方法我们只要用到一个参数,就是我们要截取的字符,我们将下划线截掉,截取的值用List装起来再toString显示出来
                var strList:List<String> = splitData.split("_")
                tv_split_result.text = strList.toString()
                split_result_lay.visibility = View.VISIBLE
            }
        }

运行效果如下图

在这里插入图片描述
在这里插入图片描述

现在常用的方法都介绍完毕了,(PS:讲真的,挺繁琐的)

3.2字符串模板及拼接

Kotlin格式化字符串,

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
var str:String = "How Are You"
        btn_format.setOnClickListener { btn_format.text = "你好吗?$str" }

我们可以看到,Kotlin中拼接字符串是很简单的,在$后面跟变量名即可,另外有可能变量会先进行计算,再把运算结果拼接到字符串中,此时需要用大括号把运算表达式给括起来,如下所示 布局文件中加一个按钮

<Button
        android:layout_marginTop="20dp"
        android:id="@+id/btn_can_format"
        android:text="计算字符串"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

代码中

var dangerous:String = "dangerous"
        btn_can_format.setOnClickListener { btn_can_format.text = "危险${dangerous.length}" }

在上面的Kotlin代码中,我们频繁用到了 $ ,美元符号,它在Kotlin中属于特殊字符,因此不能直接打印,需要经过转义后方可打印,转义的方法是使用${’***’}表达式,该表达式外层的“ ${‘’} ”为转义声明,内层的“ ** ”为需要原样输出的字符串,如下所示: 写个按钮

<Button
        android:layout_marginTop="20dp"
        android:id="@+id/btn_dollar"
        android:text="美元符号"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

代码中

var money:Int = 10
        btn_dollar.setOnClickListener { btn_dollar.text = "美元金额为${'$'}$money" }

还有另一种方式,针对于单个美元符号,如下所示:

btn_dollar.setOnClickListener { btn_dollar.text = "美元金额为\$$money" }

字符串的讲解大致就这些了

四、容器

与Java类似,Kotlin也拥有三类基本的容器,分别是集合Set、队列List、映射Map,然后每类容器又分作只读与可变两种类型,这是为了判断该容器能否进行增、删、改等变更操作,Kotlin对变量的修改操作很慎重,每个变量在定义的时候就必须指定能否修改,比如添加val修饰表示该变量不可修改,添加var修饰表示该变量允许修改。至于容器则默认为只读容器,如果需要允许修改该容器变量,就需要加上Mutable前缀形成新的容器,比如MutableSet表示可变集合,MutableList表示可变队列,MutableMap表示可变映射,只有可变的容器才能够对其内部元素进行增、删、改操作。 既然集合Set、队列List、映射Map三者都属于容器,那么他们必定拥有相同的容器方法,一些公共方法具体说明说下。 isEmpty 判断该容器是否为空。 isNotEmpty 判断该容器是否非空。 clear 清空该容器。 contains 判断该容器是否包含指定元素。 iterator 获取该容器的迭代器。 count 获取该容器包含的元素个数,也可通过size来获取。 另外,Kotlin允许在声明容器变量是就进行初始赋值,这一点在Java中是不行的,当然,不同容器的初始化方法有所不同,如下表所示

kotlin的容器

容器名称

容器的初始化方法

只读集合

Set

setOf

可变集合

MutableSet

mutableSetOf

只读队列

List

listOf

可变队列

MutableList

mutableListOf

只读映射

Map

mapOf

可变映射

MutableMap

mutableMapOf

下面我们逐个来讲解

4.1 集合Set/MutableSet

集合是一种最简单的容器,它有以下特性: (1)容器内部的元素不按顺序排列,因此无法按照下标进行访问。 (2)容器内部的元素存在唯一性,通过哈希值校验是否存在相同的元素,若存在,则将其覆盖。 因为Set是只读集合,初始化赋值后便不可更改,所以元素变更的方法只适用于可变集合MutableSet,但MutableSet的变更操作尚有以下限制 (1)MutableSetadd方法仅仅在集合中添加元素,由于集合是无序的,因此不知道添加的具体位置。 (2)MutableSet没有修改元素值的方法,一个元素一旦被添加,就不可被修改。 (3)MutableSetremove方法用于删除指定元素,但无法删除某一个位置的元素,这是因为集合的元素不是按照顺序来排列的。

对于集合的便利操作,Kotlin提供了好几种方式,有熟悉的for - in 循环、迭代器遍历,还有新的面孔forEach,下面一一进行说明

1.for-in循环 示例如下: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_marginTop="20dp"
        android:textColor="#000"
        android:padding="20dp"
        android:id="@+id/tv_set_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:layout_marginTop="20dp"
        android:id="@+id/btn_set_for"
        android:text="for-in"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

MainActivity.kt

package com.llw.kotlinstart

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val goodsMutSet:Set<String> = setOf("小米","华为","荣耀","苹果","OPPO")
        btn_set_for.setOnClickListener {
            var desc = ""
            //使用for-in语句循环取出集合中的每条记录
            for (item in goodsMutSet){
                desc = "${desc}名称:${item}\n"
            }
            tv_set_result.text = "手机畅销品牌如下${goodsMutSet.size}个品牌:\n$desc"
        }

    }
}

运行效果图如下所示:

在这里插入图片描述
在这里插入图片描述

2.迭代器遍历 迭代器与指针的慨念有点接近,它自身并非具体的元素,二十指向元素的存放地址,所以迭代器遍历其实是遍历所有元素的地址。迭代器通过hasNext方法判断是否存在下一个节点,如果不存在下一节点,就表示已经遍历完毕,他通过next方法获得下一个节点的元素,同时迭代器自身改为指向改元素的地址,下面是代码示例

activity_main.xml中加一个按钮

<Button
        android:layout_marginTop="20dp"
        android:id="@+id/btn_set_iterator"
        android:text="迭代器遍历"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

MainActivity.kt

//迭代器遍历
        btn_set_iterator.setOnClickListener {
            var desc = ""
            var iterator = goodsMutSet.iterator()
            //如果迭代器还存在洗一个节点,就继续取出下一个节点的记录
            while (iterator.hasNext()){
                var item = iterator.next()
                desc = "${desc}名称:${item}\n"
            }
            tv_set_result.text = "手机畅销品牌如下${goodsMutSet.size}个品牌:\n$desc"
        }

演示的效果和第一个图相似,

3.forEach遍历 无论是for-in循环还是迭代器遍历,都是Java已有的容器遍历操作,代码书写上不够精炼,对此,Kotlin给容器创造了forEach方法,明确指定该方法就是要依次 遍历容器内部的元素。forEach方法在编码时采用匿名函数的形式,内部用it代表每个元素,下面是运用示例代码: activity_main.xml添加

<Button
        android:layout_marginTop="20dp"
        android:id="@+id/btn_set_foreach"
        android:text="ForEach遍历"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

MainActivity.kt中新增

//forEach遍历
        btn_set_foreach.setOnClickListener {
            var desc = ""
            //forEach内部使用it指代每条记录
            goodsMutSet.forEach { desc = "${desc}名称:${it}\n" }
            tv_set_result.text = "手机畅销品牌如下${goodsMutSet.size}个品牌:\n$desc"
        }

以上关于Set/MutableSet的用法介绍完了,但是我们可以发现在实战中存在很多问题,如下: (1)集合不允许修改内部元素的值。 (2)集合无法删除指定位置的元素。 (3)不能通过下标获取指定位置的元素。 故而实际开发中基本用不到集合,都是用队列和映射(PS:此时我的内心有一万只羊驼奔腾而过~)

4.2 队列List/MutableList

	队列相对于集合来说的优势就在于有次序,优点如下:
	(1)队列能够通过get方法获取指定位置的元素,也可以直接通过下标获取该位置的元素。
	(2)MutableList的add方法每次都是把元素添加到队列末尾,也可指定添加的位置。
	(3)MutableList的add方法允许替换或者修改指定位置的元素。
	(4)MutableList的removeAt方法允许删除指定位置的元素。
	(5)队列除了拥有跟集合一样的三种遍历方式(for-in循环、迭代器遍历、forEach遍历)外,还多了一种按元素下标循环遍历的方式,示例如下:

布局文件activity_main.xml代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_marginTop="20dp"
        android:textColor="#000"
        android:padding="20dp"
        android:id="@+id/tv_list_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:layout_marginTop="20dp"
        android:id="@+id/btn_for_index"
        android:text="indices遍历"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>


</LinearLayout>

MainActivity.kt

package com.llw.kotlinstart

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val goodsMutSet:List<String> = listOf("小米","华为","荣耀","苹果","OPPO","VIVO")
        btn_for_index.setOnClickListener {
            var desc = ""
            //indices是队列的下标数组,如果队列大小为10 ,下标取值 0-9
            for(i in goodsMutSet.indices){
                val item = goodsMutSet[i]
                desc = "${desc}名称:${item}\n"
            }
            tv_list_result.text = "手机畅销品牌如下${goodsMutSet.size}个品牌:\n$desc"
        }


    }
}
在这里插入图片描述
在这里插入图片描述

MutableList提供了sort系列方法用于给队列中的元素重新排序,其中sortedBy方法表示按照指定条件升序排列,sortByedDescending方法表示按照指定条件降序排列。

4.3 映射Map/MutableMap

映射内部保存的是一组键值对(key-value),也就是说,每个元素都由两个部分构成,第一部分时元素的键,相当于元素的名字;第二部分是元素的值,存放着元素的详细信息。元素的键与值是一一对应的关系,相同键名指向的键值时唯一的,所以映射中每个元素的值各不相同,这个特性使得映射的变更操作与队列存在以下不同之处 (1)映射的containsKey方法判断是否存在指定键名的元素,containsValue方法判断是否存在指定键值的元素。 (2)MutableMap的put方法不单单是添加元素,而是智能的数据存储,每次调用put方法时,映射会先根据键名寻找同名元素,如果找不到就添加新元素,如果找得到就用新元素替换旧元素。 (3)MutableMap的remove方法是通过键名来删除元素的。 (4)调用mapOf和mutableMapOf方法初始化映射时,有两种方式可以表达单个键值对元素,其一是采取“键名 to 键值”的形式,其二是采取Pair配对方式,形如“Pair(键名,键值)”,下面是两种初始化方式的代码示例:

//to方式初始化映射
        var goodsMap:Map<String,String> = mapOf("苹果" to "iPhone",
            "华为" to "Mate20","小米" to "小米10","欧珀" to "OPPO R20", "步步高" to "VIVO X95")
        
        //Pair方式初始化映射
        var goodsMutMap:MutableMap<String,String> = mutableMapOf(Pair("苹果","iPhone"),
        Pair("华为","Mate20"),Pair("小米","小米10"),Pair("欧珀","OPPO R20"), Pair("步步高","VIVO X95"))

映射的遍历与集合类似,也有for-in循环、迭代器遍历、forEach遍历三种遍历手段。 1.for-in循环 for-in取出来的是映射的元素键值对,若要获取钙元素的键名,还需要访问元素的key属性,若要获取该元素的的键值,还需要访问元素的value属性。下面是在映射中运用for-in循环的代码示例:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_marginTop="20dp"
        android:textColor="#000"
        android:padding="20dp"
        android:id="@+id/tv_map_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:layout_marginTop="20dp"
        android:id="@+id/btn_map_for"
        android:text="Map_For"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>


</LinearLayout>

MainActivity.kt

package com.llw.kotlinstart

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //to方式初始化映射
        var goodsMap:Map<String,String> = mapOf("苹果" to "iPhone",
            "华为" to "Mate20","小米" to "小米10","欧珀" to "OPPO R20", "步步高" to "VIVO X95")

        //Pair方式初始化映射
        var goodsMutMap:MutableMap<String,String> = mutableMapOf(Pair("苹果","iPhone"),
        Pair("华为","Mate20"),Pair("小米","小米10"),Pair("欧珀","OPPO R20"), Pair("步步高","VIVO X95"))


        btn_map_for.setOnClickListener {
            var desc = ""
            //使用for-in语句循环取出映射中的每条记录
            for(item in goodsMutMap){
                //item.key 表示该配对的键,item.value 表示该配对的值
                desc = "${desc}厂家:${item.key},名称:${item.value}\n"
            }
            tv_map_result.text = "手机畅销榜包含以下${goodsMutMap.size}款手机:\n$desc"
        }

    }
}

运行效果图

在这里插入图片描述
在这里插入图片描述

2.迭代器遍历 映射的迭代器通过next函数得到下一个元素,接着需访问该元素的key属性获取键名,访问该元素的value属性获取键值,下面是在映射中运用迭代器遍历的代码示例: 布局中加一个按钮

<Button
        android:layout_marginTop="20dp"
        android:id="@+id/btn_map_iterator"
        android:text="Map_iterator"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

代码中加一段

btn_map_iterator.setOnClickListener {
            var desc = ""
            val iterator = goodsMutMap.iterator()
            //如果迭代器还存在下一个节点,就继续取出下一个节点的记录
            while (iterator.hasNext()){
                val item = iterator.next()
                desc = "${desc}厂家:${item.key},名称:${item.value}\n"
            }
            tv_map_result.text = "手机畅销榜包含以下${goodsMutMap.size}款手机:\n$desc"
        }

3.forEach遍历 映射的forEach方法内部依旧采用匿名函数的形式,同时把元素的key和value作为匿名函数的输入参数,不过映射的forEach函数需要API24及以上版本支持,开发时注意修改编译配置,下面是在映射中运用forEach遍历的代码示例: 布局文件中增加一个按钮:

<Button
        android:layout_marginTop="20dp"
        android:id="@+id/btn_map_foreach"
        android:text="Map_foreach"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

代码中增加:

btn_map_foreach.setOnClickListener {
            var desc = ""
            //forEach内部使用key指代每条记录的键,使用value指代每条记录的值
            goodsMap.forEach{ key,value -> desc = "${desc}厂家:${key},名称:${value}\n"}

            tv_map_result.text = "手机畅销榜包含以下${goodsMutMap.size}款手机:\n$desc"
        }

运行效果都是一样的,就不贴了,数据类型终于学完了,码字是比较累啊,如有错误请指出,以上内容均为自己一个一个打出来的,没有复制粘贴。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-02-19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、基本数据类型
    • 1.1变量声明
      • 1.2变量转换
      • 二、数组
        • 2.1数组元素的操作
        • 三、字符串
          • 3.1字符串与基本类型的转换
            • 3.2字符串的常用方法
              • 3.2字符串模板及拼接
              • 四、容器
                • 4.1 集合Set/MutableSet
                  • 4.2 队列List/MutableList
                    • 4.3 映射Map/MutableMap
                    相关产品与服务
                    容器服务
                    腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
                    领券
                    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档