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

<Button

android:layout_marginTop=“20dp”

android:id=“@+id/btn_string”

android:text=“测试”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”/>

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 = 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

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”/>

<Button

android:layout_marginTop=“20dp”

android:id=“@+id/btn_substring”

android:text=“截取字符串”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”/>

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

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”/>

<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

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”/>

<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 = 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 = “美元金额为KaTeX parse error: Expected '}', got 'EOF' at end of input: {''}$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”/>

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 = setOf(“小米”,“华为”,“荣耀”,“苹果”,“OPPO”)

btn_set_for.setOnClickListener {

var desc = “”

//使用for-in语句循环取出集合中的每条记录

for (item in goodsMutSet){

desc = “ d e s c 名称: {desc}名称: desc名称:{item}\n”

}

tv_set_result.text = “手机畅销品牌如下KaTeX parse error: Undefined control sequence: \n at position 23: …utSet.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 = “ d e s c 名称: {desc}名称: desc名称:{item}\n”

}

tv_set_result.text = “手机畅销品牌如下KaTeX parse error: Undefined control sequence: \n at position 23: …utSet.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 = “ d e s c 名称: {desc}名称: desc名称:{it}\n” }

tv_set_result.text = “手机畅销品牌如下KaTeX parse error: Undefined control sequence: \n at position 23: …utSet.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”/>

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 = listOf(“小米”,“华为”,“荣耀”,“苹果”,“OPPO”,“VIVO”)

btn_for_index.setOnClickListener {

var desc = “”

//indices是队列的下标数组,如果队列大小为10 ,下标取值 0-9

for(i in goodsMutSet.indices){

val item = goodsMutSet[i]

desc = “ d e s c 名称: {desc}名称: desc名称:{item}\n”

写在最后

今天关于面试的分享就到这里,还是那句话,有些东西你不仅要懂,而且要能够很好地表达出来,能够让面试官认可你的理解,例如Handler机制,这个是面试必问之题。有些晦涩的点,或许它只活在面试当中,实际工作当中你压根不会用到它,但是你要知道它是什么东西。

最后在这里小编分享一份自己收录整理上述技术体系图相关的几十套腾讯、头条、阿里、美团等公司的面试题,把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节,由于篇幅有限,这里以图片的形式给大家展示一部分。

还有 高级架构技术进阶脑图、Android开发面试专题资料,高级进阶架构资料 帮助大家学习提升进阶,也节省大家在网上搜索资料的时间来学习,也可以分享给身边好友一起学习。

【Android核心高级技术PDF文档,BAT大厂面试真题解析】

【算法合集】

【延伸Android必备知识点】

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

val goodsMutSet:List = listOf(“小米”,“华为”,“荣耀”,“苹果”,“OPPO”,“VIVO”)

btn_for_index.setOnClickListener {

var desc = “”

//indices是队列的下标数组,如果队列大小为10 ,下标取值 0-9

for(i in goodsMutSet.indices){

val item = goodsMutSet[i]

desc = “ d e s c 名称: {desc}名称: desc名称:{item}\n”

写在最后

今天关于面试的分享就到这里,还是那句话,有些东西你不仅要懂,而且要能够很好地表达出来,能够让面试官认可你的理解,例如Handler机制,这个是面试必问之题。有些晦涩的点,或许它只活在面试当中,实际工作当中你压根不会用到它,但是你要知道它是什么东西。

最后在这里小编分享一份自己收录整理上述技术体系图相关的几十套腾讯、头条、阿里、美团等公司的面试题,把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节,由于篇幅有限,这里以图片的形式给大家展示一部分。

还有 高级架构技术进阶脑图、Android开发面试专题资料,高级进阶架构资料 帮助大家学习提升进阶,也节省大家在网上搜索资料的时间来学习,也可以分享给身边好友一起学习。

【Android核心高级技术PDF文档,BAT大厂面试真题解析】

[外链图片转存中…(img-XdLAqzlc-1714505978233)]

【算法合集】

[外链图片转存中…(img-I3D15EPa-1714505978234)]

【延伸Android必备知识点】

[外链图片转存中…(img-svdsgp7S-1714505978234)]

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 21
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值