区间、数组、集合之间转换
在Kotlin中区间、数组、集合都是描述一系列元素的集合。通过上面的学习,我们看到它们有不同的地方,也有相似的地方。其实只要把其中一个的学习思路把握了。学习其他依葫芦画瓢的事情。
实际上,区间、数组、集合之间还可以相互转换。
Range转Array、List、Set
区间可以转数组,也可以转List和Set集合。转数组通过arrayOf方法,转List通过toList方法,转Set通过toSet方法。
arrayOf方法,可以接收区间参数,返回数组,参考签名:
public inline fun <reified @PureReifiable T> arrayOf(vararg elements: T): Array<T>
toList方法,转换为List,参考签名:
public fun <T> Iterable<T>.toList(): List<T> {
}
toSet方法,返回Set,参考签名:
public fun <T> Iterable<T>.toSet(): Set<T> {
}
我们通过一个案例来验证下,参考代码:
![](https://img.haomeiwen.com/i7368752/001b0da48f451f55.png)
Array转List、Set
数组可以转List和Set集合。转List通过toList方法,转Set通过toSet方法。
toList方法,转换为List,参考签名:
public fun <T> Iterable<T>.toList(): List<T> {
}
toSet方法,返回Set,参考签名:
public fun <T> Iterable<T>.toSet(): Set<T> {
}
我们通过一个案例来验证下,参考代码:
![](https://img.haomeiwen.com/i7368752/a5b53a5581a93776.png)
List转Array和Set
List可以转Array和Set集合。转Array通过toIntArray和toTypedArray,转Set通过toSet方法。
toIntArray方法,转换为Int数组,方法签名:
public fun Collection<Int>.toIntArray(): IntArray
{
}
toTypedArray方法,根据List中包含元素的类型转换为对应的集合,如果是List<String>转换为String数组,如果是List<Int>转换为Int数组,方法签名:
![](https://img.haomeiwen.com/i7368752/a6dbd9178574feba.png)
这里用到了关键字reified,这个是在泛型里面会接受的知识点。
toSet方法,返回Set,参考签名:
public fun <T> Iterable<T>.toSet(): Set<T> {
}
我们通过一个案例来验证下,参考代码:
![](https://img.haomeiwen.com/i7368752/bd26fca9e6f05ba7.png)
Set转Array和List
Set可以转Array和List集合。转Array通过toIntArray和toTypedArray,转List通过toList方法。
toIntArray方法,转换为Int数组,方法签名:
public fun Collection<Int>.toIntArray(): IntArray
{
}
toTypedArray方法,根据List中包含元素的类型转换为对应的集合,如果是List<String>转换为String数组,如果是List<Int>转换为Int数组,方法签名:
![](https://img.haomeiwen.com/i7368752/8af381cc95d3cdcd.png)
这里用到了关键字reified,这个是在泛型里面会接受的知识点。
toSet方法,返回Set,参考签名:
public fun <T> Iterable<T>.toSet(): Set<T> {
}
我们通过一个案例来验证下,参考代码:
![](https://img.haomeiwen.com/i7368752/6396bca71f373086.png)
Map转Array、List和Set
Map可以直接转List集合,那么List中所转元素的类型就是Pair。Map想要转Array、List和Set只能先获取map的keys或者values进行换行。所用的方法还是之前提到的toList、toSet、toTypedArray,所以这里就不做过多解释了,直接演示下例子:
![](https://img.haomeiwen.com/i7368752/de3909278f52af7a.png)
![](https://img.haomeiwen.com/i7368752/209948162c88ff7d.png)
网友评论