Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between @() and @{} in Powershell and when to use one over another?

I was going through some examples in powershell and see the usage of both @() and @{}. Doing a quick google search on the difference tells me that one is an array and another is hashtable.

Could you share some real-life examples where say I would like to build a hashtable and not an array? And pros/cons of one over another? Thanks in advance for your inputs!

like image 715
Pramod Yadav Avatar asked Jan 15 '20 14:01

Pramod Yadav


2 Answers

An array is simply a list of values whereas a hashtable is a collection of key/value pairs.

Here are some examples:

Array

$i = @(1,2,3,4,5)

Hashtable

[hashtable]$i = @{ Number = 1; Shape = "Square"; Color = "Blue"}
like image 138
I.T Delinquent Avatar answered Sep 25 '22 07:09

I.T Delinquent


Advantages of hash table

  • Main advantage is synchronization.

  • In many situations, hash tables turn out to be more efficient than search trees or any other table lookup structure. For this reason, they are widely used in many kinds of computer softwares, particularly for associative arrays, database indexing, caches and sets.

Disadvantages of hash table

  • Hash collisions are practically unavoidable. when hashing a random subset of a large set of possible keys.

  • Hash tables become quite inefficient when there are many collisions.

  • Hash table does not allow null values, like hash map.

Advantages of array

  • Type safe. Collects same type of data.

  • Can be accessed by indexes.

  • useful for storing less no of values.

Disadvantages of array

  • Fixed size.

  • Memory wastage. Not useful when dealing with large set of values.

like image 26
programmer365 Avatar answered Sep 24 '22 07:09

programmer365