Kotlin. Array class. Array assignment. Operator =

Array class. Array assignment. Operator =. Variables and methods of the Array class

Before studying this topic, it is recommended that you familiarize yourself with the following topic:


Contents


Search other resources:

1. Internal variables and methods of the Array class. Overview

The Array class defines the following internal variables:

  • size – returns the array size.

Operators that work with the Array class:

  • = is an operator for assigning one array to another;
  • += – operator for adding a new element to the end of the array;
  • [ ] – indexing function – get an element at the specified index. This is an analog of the set() function.

The most commonly used methods of the Array class are:

  • get() – returns the element at the given index;
  • set() – sets the value of the element at the specified index;
  • copyOf() – get a copy of the array;
  • copyOfRange() – get a copy of the array from the given range;
  • plus() – adds a new element to the array, resulting in another array with the new element;
  • plusElement() – adds a new element to the array; this is the inline implementation;
  • fill() – fills the array with the given values;
  • reverse() – reverses the array;
  • sliceArray() – allows you to get a slice of an array by a given range.

 

2. Array assignment. Operator =. Full copy of the array. Method clone()

In Kotlin, an array can be formed from another array. To do this, you can use one of the following operations:

  • the assignment operation =;
  • method clone();
  • methods copyOf(), copyOfRange() and sliceArray(). These methods are described in the following paragraphs.

If for two arrays of the same type A and B use the assignment operation

A = B

then both references A, B will point to one array (one memory area). As a result, any changes to the array will be common to both references.

To make a complete copy of array B, you need to use the clone() method

A = B.clone()

In this case, two independent arrays are created. Changes in one array will not affect changes in the other array.

 

3. Methods get(), set(). Array indexing operator [ ]. Accessing individual elements of the array

To access single elements of the array of type Array, the get() and set() methods are used. The get() method allows you to get the value of an array element at a given index. According to the documentation, the get() function declaration looks like

public final operator fun get(index: kotlin.Int): T

here

  • index – position (index) of the array element to be obtained. For the first element of the array, index is 0;
  • T – type of array elements.

The set() method sets a new value at the given index. The general form of the method declaration is as follows

public final operator fun set(index: kotlin.Int, value: T): Unit

here

  • index – the position (index) of the element in the array for which the value is set. Positions index are numbered from 0;
  • value – value written to index position.

The get() and set() methods are replaced by the indexing operation [ ]. This operation allows you to read an array element and write it to the array.

Example.

fun main(args: Array<String>) {

  // 1. Methods get(), set()
  // 1. Create an array of 3 elements
  var A : Array<Int?> = arrayOfNulls(3)

  // 2. Write numbers to array - set() method
  A.set(0, 25)
  A.set(1, 30)
  A.set(2, 18)

  // 3. Display the created array on the screen - get() method
  var i : Int = 0

  while (i<A.size) {
    println("A[" + i + "] = " + A.get(i))
    i++
  }
}

Program result

A[0] = 25
A[1] = 30
A[2] = 18

 

4. Method copyOf(). Get copy of the array

The copyOf() method copies one array to another array. The method is similar to the clone() method. The method has two overloaded implementations

public inline fun <T> Array<T>.copyOf(): Array<T>
public inline fun <T> Array<T>.copyOf(newSize: Int): Array<T?>

here

  • T – type of array elements;
  • newSize is the new size of the destination array.

Method calls can be

Dest = Source.copyOf()

or

Dest = Source.copyOf(newSize)

here

  • Dest is a new array, which is a copy of the Source array. This array is located in another area of memory;
  • Source is the source array from which the copy is made to the Dest array;
  • newSize is the size set for the Dest array.

The first implementation without parameters copies the source array to the destination array. The second implementation allows you to additionally set the size of the destination array when copying.

If the new size newSize is greater than the size of the current array, then the excess elements are filled with null values. If the value of newSize is less than the size of the current array, then the extra elements are truncated.

Example.

The example demonstrates overloaded implementations of the copyOf() method.

fun main(args: Array<String>) {

  // 1. Method copyOf()
  // 1. Create an array of 3 strings
  val A : Array<String?> = arrayOfNulls(3)

  // 2. Write strings to array A and output it
  A[0] = "abcd"; A[1] = "efgh"; A[2] = "jklmn"
  print("A => ")
  for (s in A)
    print(s + " ")
  println()

  // 3. Get a copy of the array in array B
  val B = A.copyOf()

  // 4. Output the array B
  print("B = A.copyOf() => ")
  for (s in B)
    print(s + " ") // B = abcd efgh jklmn
  println()

  // 5. Get a copy of array B with an increase in the number of elements to 5.
  //   The copy is placed in the C array.
  val C = B.copyOf(5)

  // 6. Output the array C
  print("C = B.copyOf(5) => ")
  for (s in C)
    print(s + " ") // C = abcd efgh jklmn null null
  println()

  // 7. Get a copy from array C, reducing the number of elements to 2.
  //   The copy is placed in array D.
  val D = C.copyOf(2)

  // 8. Output the array D
  print("D = C.copyOf(2) => ")
  for (s in D)
    print(s + " ")
}

Program result

A => abcd efgh jklmn
B = A.copyOf() => abcd efgh jklmn
C = B.copyOf(5) => abcd efgh jklmn null null
D = C.copyOf(2) => abcd efgh

 

5. Method copyOfRange(). Get a copy of an array from a given range

The copyOfRange() method is similar to the copyOf() method, with the difference that it allows you to specify the range of values in the source array that should be copied to the destination array.

According to the documentation, the method declaration is as follows:

public inline fun <T> Array<T>.copyOfRange(fromIndex: Int, toIndex: Int): Array<T>

here

  • T – type of array elements;
  • fromIndex – a value that specifies the start of the copy range;
  • toIndex – a value that specifies the end of the copy range.

The function copies the elements of the source array to the destination array from the fromIndex value to the toIndex value. The fromIndex and toIndex values start at 0. The value of toIndex specifies the number of the element that follows the last element in the copy range. This means that if you want to copy elements from position 0 to position 2 inclusive, the copyOfRange() function call should be as follows:

copyOfRange(0, 3)

Example.

fun main(args: Array<String>) {
  // Method copyOfRange()
  // 1. Create the array of 10 numbers of type Float
  var A : Array<Float> = arrayOf()

  // 2. Fill array with values
  for (i in IntRange(1, 10))
    A = A.plus(i.toFloat())

  // 3. Output array A
  for (i in A)
    print(i.toString() + " ")
  println()

  // 4. Get a copy from array A in the range [3; 5]
  var B = A.copyOfRange(3, 6)

  // 5. Display the array B
  for (i in B)
    print(i.toString() + " ")
}

Program result

1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0
4.0 5.0 6.0

 

6. Methods plus() and plusElement(). Add element or array to current array

The plus() and plusElement() methods are designed to increase the size of the calling (current) array by one or more elements.

According to the documentation, the plus() method has the following overloaded implementations

public operator fun <T> Array<T>.plus(element: T): Array<T>
public operator fun <T> Array<T>.plus(elements: Array<out T>): Array<T>
public operator fun <T> Array<T>.plus(elements: collections.Collection<T>): Array<T>

here

  • T – type of array elements;
  • element, elements – element or elements added to the end of the current array.

The first implementation of the plus() method adds a single element to the end of the current array. The second implementation adds an array to the end of the current array. The third implementation adds the collection to the end of the current array.

The plusElement() method declaration is as follows

public inline fun <T> Array<T>.plusElement(element: T): Array<T>

here

  • T – type of array elements;
  • element – the element that is added to the current array.

 

6.1. Method plus(). Adding single items to array. Example

 

fun main(args: Array<String>) {
  // Methods plus(), plusElement()

  // Form the array of 10 digits '0'..'9'.
  // Use the plus() method.
  // 1. Declare an empty array
  var A : Array<Char> = arrayOf()

  // 2. Array formation loop - plus() method
  for (c in '0'..'9')
    A = A.plus(c)

  // 3. Display the array
  print("A => ")
  for (c in A)
    print(c + " ")
  println()
}

Program result

A => 0 1 2 3 4 5 6 7 8 9

 

6.2. Method plus(). Adding an array to another array. Example

 

// Methods plus(), plusElement()
// Form array B based on two other arrays C and D.
// B = B + C + D
// 1. Declare arrays B, C, D and fill them with some data
var B : Array<Int> = arrayOf(1, 2, 3)
var C : Array<Int> = arrayOf(4, 5)
var D : Array<Int> = arrayOf(6, 7, 8, 9, 0)

// 2. Calculation: B = B + C + D
B = B.plus(C.plus(D))

// 3. Display the array B
print("B => ")
for (i in B)
  print(i.toString() + " ")
println()

Program result

B => 1 2 3 4 5 6 7 8 9 0

 

6.3. Method plusElement(). Adding a single element to the array. Example

The plusElement() method is used to add a single element to the end of the array. According to the documentation, the method declaration is as follows:

public inline fun <T> Array<T>.plusElement(element: T): Array<T>

here

  • T – the type of the array elements;
  • element – element to be added to the end of the current array.

Example.

fun main(args: Array<String>) {
  // Methods plus(), plusElement()

  //    Form an array of cubes of numbers from 1 to 10.
  //    Use the plusElement() method.
  // 1. Declare an empty array
  var A : Array<Double> = arrayOf()

  // 2. Array formation loop - plusElement() method
  for (x in IntRange(1, 10))
    A = A.plusElement(x.toDouble())

  // 3. Display the array
  print("A => ")
  for (x in A)
    print((x*x*x).toString() + " ")
  println()
}

Program result

A => 1.0 8.0 27.0 64.0 125.0 216.0 343.0 512.0 729.0 1000.0

 

7. Method fill(). Fill array with specified values

The fill() method fills an array with the given values in the specified range. The method has a declaration

public fun <T> Array<T>.fill(element: T, fromIndex: Int, toIndex: Int): Unit

here

  • T – type of array elements;
  • fromIndex, toIndex – optional integer values that specify the beginning and end of the filled range. The value of toIndex specifies the position that follows the last element of the range. If there are no fromIndex and toIndex values, then the entire array is filled.

Example.

fun main(args: Array<String>) {
  // Method fill()

  // 1. Declare an array of type Double with 10 elements
  var A : Array<Double?> = arrayOfNulls(10)

  // 2. Fill array with values 5.0
  A.fill(5.0)

  // 3. Display the array
  for (x in A)
    print(x.toString() + " ")
  println()

  // 4. Write the value 0.0 to the first 5 elements
  A.fill(0.0, 0, 6)

  // 5. Display the array
  for (x in A)
    print(x.toString() + " ")
}

Program result

5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0
0.0 0.0 0.0 0.0 0.0 0.0 5.0 5.0 5.0 5.0

 

8. Method reverse(). Array reversing

The reverse() method implements the reversal of the calling array. The method has a declaration

public fun <T> Array<T>.reverse(): Unit

here

  • T – the type of the array elements.

Example.

fun main(args: Array<String>) {
  // Method fill()

  // 1. Declare an array of type Short with 5 elements
  var A : Array<Short?> = arrayOfNulls(5)

  // 2. Fill array with values from 1 to 5
  for (i in IntRange(1, 5))
    A[i-1] = i.toShort()

  // 3. Display the array A
  for (d in A)
    print(d.toString() + " ")
  println()

  // 4. Reverse array
  A.reverse()

  // 5. Display the array
  for (d in A)
    print(d.toString() + " ")
}

Program result

1 2 3 4 5
5 4 3 2 1

 

9. Method sliceArray(). Get a fragment of an array within a given range

The sliceArray() method allows you to get a slice of an array within a given range. The range is specified by the IntRange type. The array declaration looks like

public fun <T> Array<T>.sliceArray(indices: ranges.IntRange): Array<T>

here

  • T – the type of array elements;
  • indices – range of elements.

Example.

fun main(args: Array<String>) {
  // Method sliceArray()

  // 1. Declare an array of type Char with 10 elements
  var A : Array<Char?> = arrayOfNulls(10)

  // 2. Fill the array with values - digits from '0' to '9'
  for (i in IntRange(0, 9))
    A.set(i, '0' + i)

  // 3. Display the array A
  for (c in A)
    print(c.toString() + " ")
  println()

  // 4. Get array fragment by range [2; 5]
  // 4.1. Declare the array
  var B : Array<Char?>

  // 4.2. Form a range
  val range : IntRange = 2..5

  // 4.3. Form array B
  B = A.sliceArray(range)

  // 5. Display the arrray
  for (c in B)
    print(c.toString() + " ")
}

Program result

0 1 2 3 4 5 6 7 8 9
2 3 4 5

 


Related topics