📅  最后修改于: 2023-12-03 14:55:04.073000             🧑  作者: Mango
Scala Array is a fixed-size, mutable collection of homogeneous elements. In simpler terms, it is a collection of elements of the same data type, and the size of the collection is fixed at the time of creation. Once created, the size cannot be changed.
To use arrays in Scala, you need to import the following package:
import Array._
You can create an array in Scala using the following syntax:
val arrayName: Array[dataType] = new Array[dataType](size)
Here, dataType
specifies the data type of the elements in the array, and size
specifies the number of elements in the array. For example:
val numbers: Array[Int] = new Array[Int](5)
This creates an array numbers
with a size of 5 that can hold integer values.
You can also initialize arrays with values using the following syntax:
val arrayName: Array[dataType] = Array(value1, value2, ..., valueN)
For example:
val fruits: Array[String] = Array("apple", "banana", "orange")
This creates an array fruits
that contains three string values.
You can access elements of an array using their index. The index of the first element is zero, and the index of the last element is size-1
. For example, to access the first element of numbers
, you would use numbers(0)
.
val firstNumber = numbers(0)
You can update elements of an array using their index. For example, to update the first element of numbers
, you could use:
numbers(0) = 123
Scala Arrays have many methods that you can use to manipulate your array. Here are a few examples:
length
MethodReturns the number of elements in the array.
val numElements = numbers.length
mkString
MethodReturns a string representation of the array.
val fruitString = fruits.mkString(", ")
This returns the string "apple, banana, orange"
.
sorted
MethodReturns a sorted copy of the array.
val sortedNumbers = numbers.sorted
reverse
MethodReturns a copy of the array with its elements in reverse order.
val reversedFruits = fruits.reverse
Scala Arrays are a simple and powerful tool for managing collections of data in your Scala programs. With their fixed-size and mutable nature, they are a versatile choice for many programming tasks.