Difference between Array and List in scala
Immutable Structures
The Scala List
is an immutable recursive data structure which is such a fundamental structure in Scala, that you should (probably) be using it much more than an Array
(which is actually mutable - the immutable analog of Array
is IndexedSeq
).
If you are coming from a Java background, then the obvious parallel is when to use LinkedList
over ArrayList
. The former is generally used for lists which are only ever traversed (and whose size is not known upfront) whereas the latter should be used for lists which either have a known size (or maximum size) or for which fast random access is important.
Mutable Structures
ListBuffer
provides a constant-time conversion to a List
which is reason alone to use ListBuffer
if such later conversion is required.
A scala Array
should be implemented on the JVM by a Java array, and hence an Array[Int]
may be much more performant (as an int[]
) than a List[Int]
(which will box its contents, unless you are using the very latest versions of Scala which have the new @specialized
feature).
However, I think that the use of Array
s in Scala should be kept to a minimum because it feels like you really need to know what is going on under the hood to decide whether your array really will be backed by the required primitive type, or may be boxed as a wrapper type.
Difference between List and Array types in Kotlin
Arrays and lists (represented by List<T>
and its subtype MutableList<T>
) have many differences, here are the most significant ones:
Array<T>
is a class with known implementation: it's a sequential fixed-size memory region storing the items (and on JVM it is represented by Java array).List<T>
andMutableList<T>
are interfaces which have different implementations:ArrayList<T>
,LinkedList<T>
etc. Memory representation and operations logic of lists are defined in concrete implementation, e.g. indexing in aLinkedList<T>
goes through the links and takes O(n) time whereasArrayList<T>
stores its items in a dynamically allocated array.val list1: List<Int> = LinkedList<Int>()
val list2: List<Int> = ArrayList<Int>()Array<T>
is mutable (it can be changed through any reference to it), butList<T>
doesn't have modifying methods (it is either read-only view ofMutableList<T>
or an immutable list implementation).val a = arrayOf(1, 2, 3)
a[0] = a[1] // OK
val l = listOf(1, 2, 3)
l[0] = l[1] // doesn't compile
val m = mutableListOf(1, 2, 3)
m[0] = m[1] // OKArrays have fixed size and cannot expand or shrink retaining identity (you need to copy an array to resize it). As to the lists,
MutableList<T>
hasadd
andremove
functions, so that it can increase and reduce its size.val a = arrayOf(1, 2, 3)
println(a.size) // will always be 3 for this array
val l = mutableListOf(1, 2, 3)
l.add(4)
println(l.size) // 4Array<T>
is invariant onT
(Array<Int>
is notArray<Number>
), the same forMutableList<T>
, butList<T>
is covariant (List<Int>
isList<Number>
).val a: Array<Number> = Array<Int>(0) { 0 } // won't compile
val l: List<Number> = listOf(1, 2, 3) // OKArrays are optimized for primitives: there are separate
IntArray
,DoubleArray
,CharArray
etc. which are mapped to Java primitive arrays (int[]
,double[]
,char[]
), not boxed ones (Array<Int>
is mapped to Java'sInteger[]
). Lists in general do not have implementations optimized for primitives, though some libraries (outside JDK) provide primitive-optimized lists.List<T>
andMutableList<T>
are mapped types and have special behaviour in Java interoperability (Java'sList<T>
is seen from Kotlin as eitherList<T>
orMutableList<T>
). Arrays are also mapped, but they have other rules of Java interoperability.Certain array types are used in annotations (primitive arrays,
Array<String>
, and arrays withenum class
entries), and there's a special array literal syntax for annotations. Lists and other collections cannot be used in annotations.As to the usage, good practice is to prefer using lists over arrays everywhere except for performance critical parts of your code, the reasoning is the same to that for Java.
Difference between List and Array
In general (and in Java) an array is a data structure generally consisting of sequential memory storing a collection of objects.
List
is an interface in Java, which means that it may have multiple implementations. One of these implementations is ArrayList
, which is a class that implements the behavior of the List
interface using arrays as the data structure.
There are a number of other classes that implement the List
interface. One easy way to take a look at them is by viewing the Javadoc for List
: http://docs.oracle.com/javase/6/docs/api/java/util/List.html
On that page, you'll see "all known implementing classes," which are all of the kinds of lists in Java.
What is the difference between List.of and Arrays.asList?
Arrays.asList
returns a mutable list while the list returned by List.of
is immutable:
List<Integer> list = Arrays.asList(1, 2, null);
list.set(1, 10); // OK
List<Integer> list = List.of(1, 2, 3);
list.set(1, 10); // Fails with UnsupportedOperationException
Arrays.asList
allows null elements while List.of
doesn't:
List<Integer> list = Arrays.asList(1, 2, null); // OK
List<Integer> list = List.of(1, 2, null); // Fails with NullPointerException
contains
behaves differently with nulls:
List<Integer> list = Arrays.asList(1, 2, 3);
list.contains(null); // Returns false
List<Integer> list = List.of(1, 2, 3);
list.contains(null); // Fails with NullPointerException
Arrays.asList
returns a view of the passed array, so the changes to the array will be reflected in the list too. For List.of
this is not true:
Integer[] array = {1,2,3};
List<Integer> list = Arrays.asList(array);
array[1] = 10;
System.out.println(list); // Prints [1, 10, 3]
Integer[] array = {1,2,3};
List<Integer> list = List.of(array);
array[1] = 10;
System.out.println(list); // Prints [1, 2, 3]
Python list vs. array – when to use?
Basically, Python lists are very flexible and can hold completely heterogeneous, arbitrary data, and they can be appended to very efficiently, in amortized constant time. If you need to shrink and grow your list time-efficiently and without hassle, they are the way to go. But they use a lot more space than C arrays, in part because each item in the list requires the construction of an individual Python object, even for data that could be represented with simple C types (e.g. float
or uint64_t
).
The array.array
type, on the other hand, is just a thin wrapper on C arrays. It can hold only homogeneous data (that is to say, all of the same type) and so it uses only sizeof(one object) * length
bytes of memory. Mostly, you should use it when you need to expose a C array to an extension or a system call (for example, ioctl
or fctnl
).
array.array
is also a reasonable way to represent a mutable string in Python 2.x (array('B', bytes)
). However, Python 2.6+ and 3.x offer a mutable byte string as bytearray
.
However, if you want to do math on a homogeneous array of numeric data, then you're much better off using NumPy, which can automatically vectorize operations on complex multi-dimensional arrays.
To make a long story short: array.array
is useful when you need a homogeneous C array of data for reasons other than doing math.
What is the difference between lists and arrays?
Take a look at perldoc -q "list and an array"
. The biggest difference is that an array is a variable, but all of Perl's data types (scalar, array and hash) can provide a list, which is simply an ordered set of scalars.
Consider this code
use strict;
use warnings;
my $scalar = 'text';
my @array = (1, 2, 3);
my %hash = (key1 => 'val1', key2 => 'val2');
test();
test($scalar);
test(@array);
test(%hash);
sub test { printf "( %s )\n", join ', ', @_ }
which outputs this
( )
( text )
( 1, 2, 3 )
( key2, val2, key1, val1 )
A Perl subroutine takes a list as its parameters. In the first case the list is empty; in the second it has a single element ( $scalar)
; in the third the list is the same size as @array
and contains ( $array[0], $array[1], $array[2], ...)
, and in the last it is twice as bug as the number of elements in %hash
, and contains ( 'key1', $hash{key1}, 'key2', $hash{key2}, ...)
.
Clearly that list can be provided in several ways, including a mix of scalar variables, scalar constants, and the result of subroutine calls, such as
test($scalar, $array[1], $hash{key2}, 99, {aa => 1, bb => 2}, \*STDOUT, test2())
and I hope it is clear that such a list is very different from an array.
Would it help to think of arrays as list variables? There is rarely a problem distinguishing between scalar literals and scalar variables. For instance:
my $str = 'string';
my $num = 99;
it is clear that 'string'
and 99
are literals while $str
and $num
are variables. And the distinction is the same here:
my @numbers = (1, 2, 3, 4);
my @strings = qw/ aa bb cc dd /;
where (1, 2, 3, 4)
and qw/ aa bb cc dd /
are list literals, while @numbers
and @strings
are variables.
difference between array and list
In C, an array is a fixed-size region of contiguous storage containing multiple objects, one after the other. This array is an "object" in the meaning which C gives to the word - basically just some memory that represents something. An object could just be an int
.
You can distinguish slightly between array objects, and array types. Often people use array objects which are allocated with malloc
, and used via a pointer to the first element. But C does also have specific types for arrays of different sizes, and also for variable-length-arrays, whose size is set when they are created. VLAs have a slightly misleading name: the size is only "variable" in the sense that it isn't fixed at compile time. It can't change during the lifetime of the object.
So, when I say an array is fixed-size I mean that the size cannot change once the array is created, and this includes VLAs. There is realloc
, which logically returns a pointer to a new array that replaces the old one, but can sometimes return the same address passed in, having changed the size of the array in place. realloc
operates on memory allocations, not on arrays in general.
That's what an array is. The C programming language doesn't define anything called a list. Can't really compare something which is well defined, with something that isn't defined ;-) Usually "list" would mean a linked list, but in some contexts or in other languages it means other things.
For that matter, in other languages "array" could mean other things, although I can't immediately think of a language where it means anything very different from a C array.
If your question really has nothing to do with C, and is a language-agnostic data-structures question, "what is the difference between an array and a linked list?", then it's a duplicate of this:
Array versus linked-list
What is the difference between a list, a tuple and an array as data structures?
Talking about "arrays" and "lists" as abstract data types without referring to any particular implementation can be a bit confusing, because those two are not very well defined.
The two Wikipedia pages List (abstract data type) and Array data type make this ambiguity somewhat evident, with uncertain statements such as "Implementation of the list data structure may provide some of the following operations:".
In many languages, there is a type called list
and a type called array
and they have some better defined meaning.
Here is a very general summary.
Lists:
- a list is linear, it is an ordered sequence of elements;
- you can access the first element of a list;
- you can add a new element to a list;
- you can access all elements of the list one after the other, starting from the first element.
That last operation is done either with "arbitrary access" (accessing elements asl[0], l[1], l[2]
, etc.) or with two operations called "head" and "tail", wherehead(l)
returns the first element ofl
andtail(l)
returns the sublist obtained by discarding the first element.
In my mind, a list of four elements looks like this:
-> 3 -> 7 -> 12 -> 9
Arrays:
- an array provides "arbitrary access" using indices (accessing elements as
a[something]
); - sometimes the index is restricted to integers between 0 and the length of the array; sometimes the index can be anything and everything;
- you can easily modify elements that you access, but you cannot necessarily add new elements.
An array which allows anything to be used as index is usually called a map
or a dict
in most languages, where array
refers strictly to linear structures indexed by integers; but in a few languages, for instance PHP, it is still called an array.
In my mind, an array of four elements looks like this:
+--+--+--+--+
| 0| 1| 2| 3|
+--+--+--+--+
| 3| 7|12| 9|
+--+--+--+--+
Tuples:
- a linear, ordered sequence of elements;
- usually can contain elements of different types, whereas in most languages, all the elements in a list must have the same type;
- usually cannot add/remove elements
- in strongly-typed languages, such as Haskell or OCaml, the type of a tuple is given by its length and the enumeration of the types used in it, for instance the tuple
(3, 7, 12.0, "9")
has type(int, int, float, string)
, and a function returning a specific type of tuple cannot suddenly return a tuple of a different type.
Tuples in strongly-typed languages are sometimes called "product types" by analogy with the Cartesian product in mathematics, and are very close to struct
in C. Tuples in weakly-typed languages are very close to lists.
Related Topics
Limiting Java Ssl Debug Logging
How to Calculate the Difference Between Two Arraylists
Generate Uml Class Diagram from Java Project
Is Memory Leak? Why Java.Lang.Ref.Finalizer Eat So Much Memory
Kill -3 to Get Java Thread Dump
Accessing the Last Entry in a Map
When Is It Ok to Catch Nullpointerexception
Generating a Random Number Between 1 and 10 Java
How to Return JSON Data from Spring Controller Using @Responsebody
How to Copy File Inside Jar to Outside the Jar
Spring Configure @Responsebody JSON Format
What's the Default Value of Char
Does Java Support Inner/Local/Sub Methods
String.Format() to Format Double in Java