Junior — Middle
What are the main differences between an array and a set, and why should you choose an array in certain cases?
sobes.tech AI
Answer from AI
An array is an ordered collection of elements where the order matters and duplicates are allowed. A set is an unordered collection of unique elements where duplicates are automatically excluded.
Main differences:
- Order: Arrays preserve the order of insertion, sets do not.
- Uniqueness: Sets store only unique elements, arrays do not.
- Access: Elements in an array can be accessed by index, in a set — no.
Why choose an array:
- When the order of elements is important.
- When duplicates are needed.
- When fast access by index is required.
Example in Swift:
let array = [1, 2, 2, 3] // preserves order and duplicates
let set: Set = [1, 2, 2, 3] // stores only unique: 1, 2, 3