Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Array and Vector

Tags:

julia

Is there a difference between Array and Vector?

typeof(Array([1,2,3]))
Vector{Int64}

typeof(Vector([1,2,3]))
Vector{Int64}

Both seem to create the same thing, but they are not the same:

Array == Vector
false

Array === Vector
false

So, what is actually the difference?

like image 703
Georgery Avatar asked Apr 12 '20 12:04

Georgery


People also ask

What's the difference between an array and vector in Java?

The length of an array is fixed once it is created, and elements cannot be added or removed before its creation. A Vector is a resizable-array that works by reallocating storage and copying the old array elements to a new array. A Vector is synchronized, whereas an array is not synchronized.

Which is better array or vector?

Vector is better for frequent insertion and deletion, whereas Arrays are much better suited for frequent access of elements scenario. Vector occupies much more memory in exchange for managing storage and growing dynamically, whereas Arrays are a memory-efficient data structure.


1 Answers

The difference is that Vector is a 1-dimensional Array, so when you write e.g. Vector{Int} it is a shorthand to Array{Int, 1}:

julia> Vector{Int}
Array{Int64,1}

When you call constructors Array([1,2,3]) and Vector([1,2,3]) they internally get translated to the same call Array{Int,1}([1,2,3]) as you passed a vector to them.

You would see the difference if you wanted to pass an array that is not 1-dimensional:

julia> Array(ones(2,2))
2×2 Array{Float64,2}:
 1.0  1.0
 1.0  1.0

julia> Vector(ones(2,2))
ERROR: MethodError: no method matching Array{T,1} where T(::Array{Float64,2})

Also note the effect of:

julia> x=[1,2,3]
3-element Array{Int64,1}:
 1
 2
 3

julia> Vector(x)
3-element Array{Int64,1}:
 1
 2
 3

julia> Vector(x) === x
false

So essentially the call Vector(x) makes a copy of x. Usually in the code you would probably simply write copy(x).

A general rule is that Array is a parametric type that has two parameters given in curly braces:

  • the first one is element type (you can access it using eltype)
  • the second one is the dimension of the array (you can access it using ndims)

See https://docs.julialang.org/en/v1/manual/arrays/ for details.

like image 70
Bogumił Kamiński Avatar answered Oct 07 '22 16:10

Bogumił Kamiński