Range

An interval is a mathematical concept that represents a range.

Interval declaration

Kotlin can use.. Or until to declare the interval:

val range: IntRange = 0.1024. // closed range [0,1024], including 1024
val rangeExclusive: IntRange = 0 until 1024 // half-open interval [0,1024], excluding 1024
val emptyRange: IntRange = 0.. -1 // empty interval []
Copy the code

Actually, the… The rangeTo() operator corresponds to a rangeTo() method in the Int class:

/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Byte): IntRange
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Short): IntRange
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Int): IntRange
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Long): LongRange
Copy the code

Interval common operations

Determine whether an element is in the interval:

println(range.contains(50)) // true
println(500 in range) // true
Copy the code

The in keyword here corresponds to the contains() method in the IntRange class, so the above two lines are essentially the same.

Determine whether the interval is empty:

println(rangeExclusive.isEmpty()) // false
println(emptyRange.isEmpty()) // true
Copy the code

Traversal the interval:

// Output: 0, 1, 2, 3..... 1020, 1021, 1022, 1023,
for (i in rangeExclusive) {
    print("$i,")}Copy the code

In and for can be used together to achieve the traversal effect of the interval.

Type of interval

All ranges are subclasses of ClosedRange, with IntRange being the most commonly used. In addition to IntRange, ClosedRange subclasses include LongRange, CharRange, etc.

Using CharRange as an example, we can also write an interval of 26 upper and lower case letters:

// a b c d e f g h i j k l m n o p q r s t u v w x y z
val lowerRange: CharRange = 'a'.'z'
// A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
val upperRange: CharRange = 'A'.'Z'
Copy the code

Array

An Array has nothing to do with a Number. It’s a list of objects.

Create an array

There are generally two ways to create arrays:

  1. useArrayClass create array
  2. Using library functionsarrayOfXXX()Create an array

useArrayClass create array

Let’s look at the Array constructor:

public class Array<T> {
    /** * Creates a new array with the specified [size], where each element is calculated by calling the specified * [init] function. The [init] function returns an array element given its index. */
    public inline constructor(size: Int.init: (Int) -> T)

    ...
}
Copy the code

To create an Array using Array, specify the element type (usually omitted), and pass two mandatory parameters: Array size and element initialization function init.

val array = Array<String>(5) { index -> "No.$index" }
println(array.size) / / 5
for (str in array) { // No.0 No.1 No.2 No.3 No.4
    print("$str ")}Copy the code

When a function argument is the last parameter, you can write it outside the parentheses, which is Kotlin’s lambda notation, or you can write it inside the parentheses without lambda notation: Val array = array

(5, {index -> “No.$index”});

Using library functionsarrayOfXXX()Create an array

ArrayOfXXX () : arrayOfXXX() : arrayOfXXX(); arrayOfXXX() : arrayOfXXX(); arrayOfXXX() : arrayOfXXX();

val arrayOfString: Array<String> = arrayOf("我"."Yes"."LQR")
val arrayOfHuman: Array<Human> = arrayOf(Boy("Moderate"."Handsome"."Deep"), Girl("Tender"."Sweet"."Moving"))
val arrayOfInt: IntArray = intArrayOf(1.3.5.7)
val arrayOfChar: CharArray = charArrayOf('H'.'e'.'l'.'l'.'o'.'W'.'o'.'r'.'l'.'d')
Copy the code

Note that arrays of objects of String or custom types are created using arrayOf(), whereas arrays of primitive data types are created using library functions such as intArrayOf(), charArrayOf(), and so on. Library functions such as intArrayOf() and charArrayOf() were created by Kotlin to avoid the overhead of basic data boxing, such as: IntArrayOf (1, 3, 5, 7) creates arrays of type IntArray, which corresponds to Java int[], and arrayOf(1, 2, 3, 4) creates arrays of type Array< int >. The corresponding value in Java is Integer[].

Array of primitive data types

To avoid unnecessary boxing and unboxing, the array of basic data types is customized:

Java Kotlin
int[] IntArray
short[] ShortArray
long[] LongArray
float[] FloatArray
double[] DoubleArray
char[] CharArray

Note: IntArray and Array

are completely different types and cannot be converted directly to each other! Kotlin also has special classes for representing arrays of native types with no boxing overhead: ByteArray, ShortArray, IntArray, and so on. These classes do not inherit from Array, but they share the same set of method attributes.

Learn more Kotlin array of relevant knowledge, please visit: www.kotlincn.net/docs/refere.

Common operations on arrays

We can use.size to get the array length, and use for-in to iterate through the array:

println(arrayOfInt.size) / / 4
for (int in arrayOfInt) { // 1 3 5 7
    print("$int ")}Copy the code

Array defines the get and set functions (which are converted to [] by operator overloading convention), so we can use [] to get or modify elements in an Array:

println(arrayOfHuman[1]) // I have a gentle personality, a sweet face and a charming voice
arrayOfHuman[1] = Boy(Moderate "1"."Handsome 1".1. "it")
println(arrayOfHuman[1]) // I am a gentle, handsome man with a deep voice
Copy the code

Note: a custom object type println () the default output is object address information, such as: com. Charylin. Kotlinlearn. Boy @ 7440 e464, need to rewrite the class toString () method to modify the output log content.

CharArray provides the joinToString() method, which is used to concatenate an array of characters into a string.

println(arrayOfChar.joinToString()) // H, e, l, l, o, W, o, r, l, d
println(arrayOfChar.joinToString("")) // HelloWorld
Copy the code

Arrays can be sliced using the slice() method:

println(arrayOfInt.slice(1.2.)) / / [3, 5]
Copy the code