Confucius said: “studious almost know, acting nearly benevolence, shame-awareness near yong”, “rites”

In practical development, the use of collections can be said to be numerous. However, there is a big difference between Kotlin and Java in the use of collections. In addition to the difference in the initialization of collections, Kotlin packages a lot of higher-order functions for collections so that we can write code more easily and more quickly. But before I go into collections, I’m going to do a little bit about the Array types in Kotlin, which you can think of as a little bit about Array

.

directory

Array types

The Kotlin array type is not a collection, but it has too much in common with collections. And arrays and sets are interchangeable. And you can also pass in an array when you initialize the collection.

Here are just a few common ones. In fact, these methods are explained later in the article.

  • witharr[index]Gets the element.
  • withArr.com ponent1 ()... arr.component5()Gets the first five elements of the array. The same applies to sets.
  • witharr.reverse()Invert the element.
  • As for the other elements treated, they are explained at the end of the article. That’s why I put array types and collection types in the same article.

Example 1: Use componentX()

val arr = arrayOf("1".2.3.4)



println(arr.component1())

println(arr.component3())



// The program crashes because there are only 4 elements, so it is safer to use these functions with caution if the number of elements is not determined.

println(arr.component5())       

Copy the code

Output result:

1

3

Copy the code

Example 2: Reverse elements

val arr = arrayOf("1".2.3.4)

arr.reverse(a)



ForEach higher-order functions will be explained later in this article. thanforThe loop is much cleaner

for (index in arr){

    print("$index \t")

}

Copy the code

Output result:

4    3    2    1

Copy the code

Second, set types

Sets in Kotlin differ from other languages in that Kotlin sets can be divided into mutable and immutable sets.

In Kotlin, there are three types of Set types: List, Set, and Map. There are similarities and differences among them as follows:

  1. These are interfaces, not actual classes.
  2. They just happenIsEmpty (), size, contains()Functions and attributes.
  3. ListandSetInherit –CollectionInterface, andCollectionInheritance in可迭代Interface. whileMapIs a separate interface. To this point andJavaThe same.
  4. These three collection types exist separatelyMutableList, MutableSet, and MutableMap interfacesThese interfaces provide methods for changing and manipulating collections. For example,add(),clear(),remove()Etc. Function.

From the above points, we can see that the Set is an immutable Set if List

, Set

, Map

are used when defining the Set type variables. MutableList

, MutableSet

, and MutableMap

are mutable types. Here I will not provide the source code to analyze, interested can have a look at the source code! The source is in kotlin\collections\ collections.kt file
,v>


,v>

2.1. List type

We know that an interface cannot be instantiated directly, so how do we initialize one? In fact, Kotlin provides us with the corresponding standard library functions to handle.

  • Declare and initialize a collection of lists: uselistOf(..)function
  • Declare and initialize a collection of MutableList: usemutableListOf(..)function

Example 1: Initialize an immutable collection of List types using listOf()

val arr = arrayOf("1"."2".3.4.5)   

val list1 = listOf(1.2."3".4."5")                // Create it at will

val list2 = listOf<String>("1"."2"."3"."4"."5")  // Determine the element's value type

val list3 = listOf(arr)                          // An array can be passed in



// The following code is incorrect. Because List can only be an immutable set. The add, remove, and clear functions are MutableList functions

// list1.add()

// list1.remove



/ / traverse

for(value in list1){

    print("$value \t")

}

Copy the code

Output result:

One, two, three, four, five

Copy the code

Example 2: Initialize a mutable collection of List types using mutableListOf()

val arr = arrayOf("1".2.3.4)

val mutableList1 = mutableListOf(1.2."3".4."5")                // Create it at will

val mutableList2 = mutableListOf<String>("1"."2"."3"."4"."5")  // Determine the element's value type

val mutableList3 = mutableListOf(arr)                          // An array can be passed in

val mutableList : ArrayList<String>  // ArrayList<> is the same as Java ArrayList



mutableList1.add("6")  // Add elements

mutableList1.add("Seven")

mutableList1.remove(1)   // Delete an element



/ / traverse

for(value in mutableList1){

    print("$value \t")

}



mutableList1.clear()   // Clear the collection

Copy the code

The output is:

2, 3, 4, 5, 6, 7

Copy the code

2.2. Set type

The Set collection is used in much the same way as the List collection. I won’t go into detail here, except to show you how it differs from a List collection.

  • Declare and initialize a collection of sets: usesetOf(..)function
  • Declare and initialize a collection of MutableSet: usemutableSetOf(..)function

Example 1: Declare and initialize

val set1 = setOf(1.2."3"."4"."2".1.2.3.4.5)

val mutableSet1 = mutableSetOf(1.2."3"."4"."2".1.2.3.4.5)

val mutableSet2 : HashSet<String>  // The HashSet<> is the same as the Java HashSet<>

Copy the code

Example 2: Iterate through the collection to see how it differs from what you expected

/ / traverse

for(value in set1){

    print("$value \t")

}

Copy the code

Output result:

1, 2, 3, 4, 2, 3, 4, 5

Copy the code

In our expected effect, the result of the traversal should be: 1, 2, 3, 4, 2, 1, 2, 3, 4, 5, but the result is missing a 1, 2. So we can see that a Set of types removes duplicate elements. This coincides with Java. This feature is also what distinguishes a collection of sets from a List collection.

2.3 Map type

A Set of Map

types is different from a List or Set. Let’s look at the declaration and initialization of a collection of Map types.
,v>

Like the previous two types, maps are also classified as immutable and mutable collections. Among them:

  • immutableThe Map typeInitialization of collections using:mapOf()function
  • variableThe Map typeInitialization of collections using:mutableMapOf()function

Initialization differs from the previous two types, however, in that the Map collection type appears as a key-value pair. Ex. :

// in the form of key-value pairs, using to between keys and values

val map1 = mapOf("key1" to 2 , "key2" to 3)

val map2 = mapOf<Int,String>(1 to "value1" , 2 to "value2")

val mutableMap = mutableMapOf("key1" to 2 , "key1" to 3)

val hashMap = hashMapOf("key1" to 2 , "key1" to 3)   // Same as Java HashMap



map2.forEach{

    key,value -> println("$key \t $value")

}

Copy the code

The output is:

1      value1

2      value2

Copy the code

PS: When there are duplicates in our key, the set will filter out the previous duplicates.

Ex. :

val map = val map1 = mapOf("key1" to 2 , "key1" to 3 , "key1" to "value1" , "key2" to "value2")



map.forEach{

    key,value -> println("$key \t $value")

}

Copy the code

The output is:

key1      value1

key2      value2

Copy the code

As you can see from the above example, when the key value is key1, the element retains only the last element. All elements with the same key are filtered out.

Covariation of set types

Imagine that when one set is assigned to another set, in this case List

, the assignment is fine if the two sets are of the same type, E. If the type is different, when E inherits from M. You can then assign List

to List

. This situation is called covariation


Case 1:

open class Person(val name : String , val age : Int) {

    override fun toString(a): String {

        return "Person(name='$name', age=$age)"

    }

}



class Student(name: String, age : Int, cls : String) : Person(name, age)



// Note that Any is the superclass in Kotlin, so the Student class inherits from Any. Here you can change the Person class and it's going to be the same

var listPerson: List<Any>

val listStudent : List<Student> = listOf(Student("Zhang".12."Class"),Student("Fifty".20."Class 2"))

listPerson = listStudent



listPerson.forEach { println(it.toString()) }

Copy the code

Output result:

Person(name='Joe', age=12)

Person(name='Cathy', age=20)

Copy the code

Example 2: When sets of the same type or inheritance relationship, one set uses MutableList and the other uses List.

var mutableListPerson: MutableList<Person>

val mutableListStudent : List<Student> = listOf(Student("Zhang".12."Class"),Student("Fifty".20."Class 2"))

mutableListPerson = mutableListStudent.toMutableList()

mutableListPerson.add(Person("a".15))

mutableListPerson.add(Person("b".45))



mutableListPerson.forEach { println(it.toString()) }

Copy the code

The output is:

Person(name='Joe', age=12)

Person(name='Cathy', age=20)

Person(name='a', age=15)

Person(name='b', age=45)

Copy the code

Look at example 2 above, which uses a toMutableList() function that converts a List to a MutableList. In the following source code we can see: instantiate an ArrayList.

public fun <T> Collection<T>.toMutableList(a): MutableList<T> {

    return ArrayList(this)

}



public fun <T>可迭代<T>.toMutableList(a): MutableList<T> {

    if (this is Collection<T>)

        return this.toMutableList()

    return toCollection(ArrayList<T>())

}

Copy the code

The covariant Set and Map sets are similar to the above code, but call different conversion functions. In addition to the toMutableList() function, there are toList(), toHashSet(), toSet() and so on. These functions are extensions of the Iterable interface. You can have a look at the source code, do not do the detailed description here.

Some commonly used extension functions for handling set types

In addition to toList(), toSet(), toHastSet(), toMutableList(), toSet(), toIntArray() and other extended functions mentioned above. There are also some commonly used extended higher-order functions. All the source code is in the kotlin\collections\ _collections.kt file.

However, due to the length of this article, the content of this section will be covered in the next chapter.

conclusion

In this article, several types of collection declaration and use are explained in detail, and the Array type Array

is also reviewed. In fact, the content of this article is not very much, you mainly remember a few standard functions of collection type initialization, and collection type covariant. The next article will cover common functions that work with collections and arrays, as well as the source code.

This article has been collected on GitHub: Jetictors/KotlinLearn, welcome star articles continue to update, can be wechat search “J guy talk” first time read, everyone’s three-in-one is the best power for the old J, you are sure not to wave? If you have any mistakes or suggestions on this blog, please leave comments


Ah hello, five fingers mushroom niang ah, take a phone to scan!