Questions tagged [arrays]

An array is an ordered linear data structure consisting of a collection of elements (values, variables, or references), each identified by one or more indexes. When asking about specific variants of arrays, use these related tags instead: [vector], [arraylist], [matrix]. When using this tag, in a question that is specific to a programming language, tag the question with the programming language being used.

An array is an ordered linear data structure consisting of a collection of elements (values or variables), each identified by at least one index, stored in contiguous memory locations.

An array is typically stored so that the position of each element can be computed from its index tuple by a mathematical formula.

In some languages (C, Java, etc.) the length of the array must be set beforehand. In other languages (Ruby, Python, LISP, Haxe, etc.) the length of the array grows dynamically as elements are added.

When tagging a question with this tag, also tag the question with the programming language being used.

Array in specific languages

  • C# arrays are actually objects and not just addressable regions of contiguous memory as in C and C++. Array is the abstract base type of all array types. You can use the properties and other class members of the Array base type.
  • C arrays act to store related data under a single variable name with an index, also known as a subscript. They are stored in row-major order, which means the last subscript varies fastest. It is easiest to think of an array as simply a list or ordered grouping for variables of the same type. As such, arrays often help a programmer organize collections of data efficiently and intuitively.
  • C++ inherits raw arrays from C and adds its own array-class std::array for compile-time array sizes, std::vector for runtime dynamic sized arrays. It also has smart pointer implementations like std::unique_ptr, std::shared_ptr.
  • Objective C inherits raw arrays from C and adds its own array-class NSArray and NSMutableArray for dynamic arrays.
  • Ruby's normal array class is called array.
  • In Python, the normal array datatype is called a list, while the array type is used for homogeneous arrays.
  • In NumPy there is a powerful N-dimensional array with many capabilities.
  • PHP arrays are implemented as ordered maps which may contain a mix of numeric or string keys.
  • JavaScript arrays are just objects with a different prototype (with additional functions more useful for array-like structures), with numerical index values stored as strings (all JavaScript keys are strings). Unlike other objects, you cannot use dot notation to access keys - only square bracket notation.
  • In Haxe, an Array has one type parameter which corresponds to the type of collection of elements. Arrays can be created using their constructor new Array() or [1, 2, 3], but also using Array comprehension: [for (i in 0...10) if (i % 2 == 0) i]. For storage of fixed size the abstract type haxe.ds.Vector can be used, which may be faster than Array on some targets and is never slower.
  • In Scala, the normal array class is called Array. To get an element from an array you use parentheses (most languages use square brackets).
  • In Java, an array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
  • In Perl, array variables are denoted with the @ prefix and arrays are declared with parentheses. Replacing the prefix with $# returns the last index.
  • In Rust, arrays are groups of data of the same type that are contiguous in memory, so they can be used when communicating with C. The length of an array is fixed.
  • In Swift, an array that includes the specified values, automatically inferring the array’s Element type. Swift makes it easy to create arrays in your code using an array literal: simply surround a comma-separated list of values with square brackets.
  • In Pascal, arrays declarations specify the index range rather than the number of elements; so parray: array [1..25] of real; declares a one-based array of 25 real numbers (valid elements are parray[1] thru parray[25]), whereas parray: array [0..24] of real; declares a zero-based ('C-style') array of the same size (the first element is parray[0]). Pascal array index ranges can include negative numbers!

Characteristics

Elements of an array are usually specified with a 0-first index, for example, myarray[0] would represent the first element of myarray. myarray[n] (where n is the length of the array minus 1) would represent the last element in the array. However, some languages such as old Fortran and Lua use 1 as the initial index.

Some languages (C++, Java, C#) have "basic arrays" and collections. Basic arrays are supported by the compiler directly, have a fixed size, and only provide element access by index. Collections, like Java's ArrayList, are system library classes implemented on the top of these basic arrays and have a wide range of various methods. In such cases, the tag should be used to name the simple arrays.

Arrays can be statically allocated or dynamically allocated. The way in which you access the array and its type varies based on how it is declared and allocated.

Arrays can contain multiple indices. For example, an array with one index (e.g. array[0]) is known as a one-dimensional array. If it has two indices (e.g. array[0][0]) it is considered two dimensional and maybe visualized as a grid. Multidimensional arrays, or, in other words, arrays with multiple indices are called matrices, or a matrix is singular.

References

Related tags

Where talking about specific variants of arrays, use these related tags instead:

414766 questions
72
votes
3 answers

how to flatten a 2D list to 1D without using numpy?

I have a list looks like this: [[1,2,3],[1,2],[1,4,5,6,7]] and I want to flatten it into [1,2,3,1,2,1,4,5,6,7] is there a light weight function to do this without using numpy?
wakeupbuddy
  • 971
  • 1
  • 8
  • 17
72
votes
8 answers

What is the idiomatic way to slice an array relative to both of its ends?

Powershell's array notation has rather bizarre, albeit documented, behavior for slicing the end of arrays. This section from the official documentation sums up the bizarreness rather well: Negative numbers count from the end of the array. For…
alx9r
  • 3,675
  • 4
  • 26
  • 55
72
votes
2 answers

check how many elements are equal in two numpy arrays python

I have two numpy arrays with number (Same length), and I want to count how many elements are equal between those two array (equal = same value and position in array) A = [1, 2, 3, 4] B = [1, 2, 4, 3] then I want the return value to be 2 (just 1&2…
Shai Zarzewski
  • 1,638
  • 3
  • 19
  • 33
72
votes
14 answers

Populating a Boolean Array in Java

As a fairly green Java coder I've set myself the hefty challenge of trying to write a simple text adventure. Unsurprisingly, I've encountered difficulties already! I'm trying to give my Location class a property to store which exits it contains.…
lordchancellor
  • 3,847
  • 4
  • 26
  • 26
72
votes
2 answers

Array of strings in groovy

In ruby, there is a indiom to create a array of strings like this: names = %w( lucas Fred Mary ) Is there something like that in groovy?
Lucas
  • 3,059
  • 5
  • 33
  • 48
72
votes
1 answer

Removing value from array on specific location

I realise there is a lot of topics on this subject but I believe this one is different: The goal is to get an value from an array on a random location then delete this value. I use this part by John Resig (the creator of jQuery) to remove an element…
GdeBrock
  • 723
  • 4
  • 6
72
votes
10 answers

How to add elements of a string array to a string array list?

I am trying to pass a string array as an argument to the constructor of Wetland class; I don't understand how to add the elements of string array to the string array list. import java.util.ArrayList; public class Wetland { private String…
robinhood91
  • 1,641
  • 3
  • 20
  • 36
72
votes
7 answers

How do I convert an array of strings into a comma-separated string?

I have an array: array = ["10", "20", "50", "99"] And I want to convert it into a simple comma-separated string list like this: "10", "20", "50", "99"
Kashiftufail
  • 10,815
  • 11
  • 45
  • 79
72
votes
8 answers

How do I convert Double[] to double[]?

I'm implementing an interface that has functionality similar to a table that can contain an types of objects. The interface specifies the following function: double[] getDoubles(int columnIndex); Where I'm stumped is that in my implementation, I'm…
Brian
  • 2,375
  • 4
  • 24
  • 35
72
votes
2 answers

Remove elements of one array if it is found in another

Possible Duplicate: Remove item from array if it exists in a 'disallowed words' array I have a dynamic string that clients will send and I want to create comma delimited tags from it: $subject = "Warmly little in before cousin as sussex and an…
Tower
  • 1,287
  • 3
  • 15
  • 25
71
votes
7 answers

Convert Eigen Matrix to C array

The Eigen library can map existing memory into Eigen matrices. float array[3]; Map(array, 3).fill(10); int data[4] = 1, 2, 3, 4; Matrix2i mat2x2(data); MatrixXi mat2x2 = Map(data); MatrixXi mat2x2 = Map(data, 2, 2); My…
lil
  • 2,527
  • 4
  • 22
  • 15
71
votes
24 answers

Convert multidimensional array into single array

I have an array which is multidimensional for no reason /* This is how my array is currently */ Array ( [0] => Array ( [0] => Array ( [plan] => basic ) [1] => Array ( …
CuriousMind
  • 33,537
  • 28
  • 98
  • 137
71
votes
8 answers

Returning an empty array

I'm trying to think of the best way to return an empty array, rather than null. Is there any difference between foo() and bar()? private static File[] foo() { return Collections.emptyList().toArray(new File[0]); } private static File[] bar() { …
Moonbeam
  • 2,283
  • 1
  • 15
  • 17
71
votes
8 answers

Is there a better PHP way for getting default value by key from array (dictionary)?

In Python one can do: foo = {} assert foo.get('bar', 'baz') == 'baz' In PHP one can go for a trinary operator as in: $foo = array(); assert( (isset($foo['bar'])) ? $foo['bar'] : 'baz' == 'baz' ); I am looking for a golf version. Can I do it…
Yauhen Yakimovich
  • 13,635
  • 8
  • 60
  • 67
71
votes
2 answers

Tensorflow: How do I convert a EagerTensor into a numpy array?

With standard Tensorflow: import tensorflow as tf x = tf.convert_to_tensor([0,1,2,3,4], dtype=tf.int64) y = x + 10 sess = tf.InteractiveSession() sess.run([ tf.local_variables_initializer(), tf.global_variables_initializer(), ]) coord =…
wewlie
  • 711
  • 1
  • 5
  • 5