Sobes.tech
Junior

What is the difference between List and Set in Dart?

sobes.tech AI

Answer from AI

Main differences:

  • Content: List can contain duplicates, Set stores only unique elements.
  • Order: List maintains the order of insertion, Set does not guarantee order.
  • Performance:
    • Adding/removing: On average, adding/removing an element in a Set is faster (O(1)) due to hashing. For List, these operations can be slower (up to O(n)) depending on the position.
    • Searching: In a Set, searching for an element by value is faster (O(1) on average) again due to hashing. In a List, searching by value requires iteration (O(n)). Accessing an element by index in a List is fast (O(1)).

Examples:

// List - allows duplicates, maintains order
List<int> numbersList = [1, 2, 2, 3, 1];
print(numbersList); // Outputs: [1, 2, 2, 3, 1]
print(numbersList[0]); // Outputs: 1 (access by index)

// Set - only unique elements, order not guaranteed
Set<int> numbersSet = {1, 2, 2, 3, 1};
print(numbersSet); // Outputs: {1, 2, 3} (order may vary)
// print(numbersSet[0]); // Error: Set does not support access by index
print(numbersSet.contains(2)); // Outputs: true (fast search)
What is the difference between List and Set in Dart… - sobes.tech