Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set vs Array , difference

Tags:

What is the difference between Set and Array in Ruby except for the fact that sets keep unique elements while arrays can keep duplicate elements?

like image 660
Mellon Avatar asked Dec 01 '11 08:12

Mellon


People also ask

What is difference between array and Set?

One of the biggest differences between an Array and a Set is the order of elements. The documentation describes this as well: Array: “An ordered, random-access collection.” Set: “An unordered collection of unique elements.”

What is the difference between Set and array in JS?

The Set data type was introduced in ES2015 and the difference between array and set is that while an array can have duplicate values a set can't. Elements can be accessed in array using index which isn't possible in Set since it uses keys and elements can be traversed only in the way they were entered.

Which is faster array or Set?

In a direct comparison, Sets have several advantages over arrays, especially when it comes to a faster run-time: Search for an Item: Using indexOf() or includes() to check whether an item exists in an array is slow. Deleting an Item: In a Set, you can delete an item by its value.

Is Set same as array in Java?

In addition, Array is considered as “indexed collection” type of data structure, while Set is considered as “keyed collection”. Keyed collections are collections which use keys; these contain elements which are iterable in the order of insertion.


2 Answers

They are very different.

Array

  • An array is an ordered list of objects.
  • An array value can be accessed by referencing its integer position in the list (zero-indexed): a[3] references the 4th object in the array.
  • There is no restriction on what the values can be—duplicate values are allowed in arrays.
  • An array has an object literal notation: [1, 'apple', String, 1, :banana] (this creates and initializes a new Array).
  • Arrays are built in to the core ruby library.

Set

  • A set is an unordered pool of unique objects.
  • Since it's unordered, there is no integer index you can use to access specific elements of a set.
  • The uniqueness restriction means you can't have more than one copy of a value in the set.
  • Set is not part of the core, but part of the standard library, and thus needs a require 'set'.
  • Before Ruby 2.4, there was no object literal notation for sets, you had to create them via Set.new.
    • For Ruby >= 2.4.0 you can use Set[] (e.g. Set[1,2,3])
like image 76
Ben Lee Avatar answered Oct 19 '22 13:10

Ben Lee


For me the main difference is that Sets are implemented as hashes, so you have O(1) membership tests for elements.

like image 40
Michael Kohl Avatar answered Oct 19 '22 12:10

Michael Kohl