Junior — Middle
What are the main differences between a Set collection and an array in programming?
sobes.tech AI
Answer from AI
A Set collection and an array (List) differ in the following main characteristics:
- Uniqueness of elements: Set stores only unique elements; duplicates are automatically ignored. An array can contain repeated values.
- Order of elements: In most implementations, Set does not guarantee the order of elements, whereas an array preserves the order of insertion.
- Access by index: In an array, you can access an element by its index, but in a Set — no, since it is not indexed.
- Performance of operations: Checking for the presence of an element in a Set is usually faster (O(1) for hash sets) than in an array (O(n)).
Example in Dart (Flutter):
var list = [1, 2, 2, 3];
var set = {1, 2, 2, 3};
print(list); // [1, 2, 2, 3]
print(set); // {1, 2, 3}