Home

Array

Array

An array is a single object that stores references to a (possibly large) number of element objects.

Array is a parameterized type: the type of the elements is a type parameter of Array. So Array[Int] is an array of integers, Array[String] and array of strings, and so on.

If you already have the elements, you can create an array like this:

scala> val a = Array(13, 29, 37, 55)
a: Array[Int] = Array(13, 29, 37, 55)
scala> val b = Array("CS109", "is", "fun")
b: Array[java.lang.String] = Array(CS109, is, fun)

Otherwise, you create an array using the new keyword, and providing the length of the array as an argument:

scala> val c = new Array[Int](20)
c: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
scala> val d = new Array[String](10)
d: Array[String] = Array(null, null, null, null, null, null, null, null, null, null)
(Note that the elements are initialized to null, except for the number types, which are initialized to 0. An Array[Boolean] is initialized to false.)

The elements of an array L are accessed as L(0) to L(L.length-1). Scala uses normal round parentheses to access the elements of an array, not square brackets like Java, C, or Python.

The length of an array is fixed when you create it—you cannot append elements or change its length in any way (see ArrayBuffer if you need to do this).

The most useful methods of arrays are the common methods of all sequences.

Examples

scala> val L = Array("CS109", "is", "the", "best")
L: Array[java.lang.String] = Array(CS109, is, the, best)
scala> L.head
res0: java.lang.String = CS109
scala> L.last
res1: java.lang.String = best
scala> L.mkString
res2: String = CS109isthebest
scala> L.mkString(" ")
res3: String = CS109 is the best
scala> L.mkString("--")
res4: String = CS109--is--the--best
scala> L.mkString("<", "_", ">")
res5: String = <CS109_is_the_best>
scala> (L.min, L.max)
res6: (java.lang.String, java.lang.String) = (CS109,the)
scala> L.sorted
res7: Array[java.lang.String] = Array(CS109, best, is, the)
scala> L.reverse
res8: Array[java.lang.String] = Array(best, the, is, CS109)
scala> L ++ Array("course", "at", "KAIST")
res9: Array[java.lang.String] = Array(CS109, is, the, best, course, at, KAIST)
scala> L :+ "course"
res10: Array[java.lang.String] = Array(CS109, is, the, best, course)
scala> "The" +: L
res11: Array[java.lang.String] = Array(The, CS109, is, the, best)