lino arango
lino arango

Reputation: 142

How to insert in set at specific index

I have a set in my program

Set<MyObject> set = {};

after inserting some values

set.add(object);

how do i insert in the set at index 0?

set.insert(index, object,);

(insert does not exists in set class) https://api.dart.dev/stable/2.8.4/dart-core/Set-class.html

Upvotes: 0

Views: 1795

Answers (2)

jamesdlin
jamesdlin

Reputation: 90055

By default Set is a LinkedHashSet, which stores items in insertion order.

As Alok suggested, using a List instead of a Set would give you full control over element order, but it would come at the cost of needing to check for element uniqueness yourself. Consequently, insertions, removals, and lookups each would be O(n) instead of the usual O(1). If you frequently need to remove elements or frequently need to check if an element already exists, this would not be an efficient solution.

If you don't need full control over element order, you might be able to continue using a Set. To force an item to be at the beginning, you would need to remove and re-add all other items. One way to do that would be to create a new Set:

set = <MyObject>{object, ...set};

If you need to mutate an existing Set, you could add an extra step:

var temporarySet = <MyObject>{object, ...set};
set..clear()..addAll(temporarySet);

Note that in both cases, insertion would have runtime complexity of O(n) instead of the usual O(1). Removals and lookups would remain O(1).

If you need to insert at the beginning frequently and only at the beginning, you possibly could cheat by always iterating over the Set backwards, treating the last element as the first:

// Force `object` to be last.
set..remove(object)..add(object);

and then use set.last instead of set.first or use set.toList().reversed when iterating. This would allow insertions, removals, and lookups to continue being O(1).

Upvotes: 1

Alok
Alok

Reputation: 9008

Following OldProgrammer's suggestion, you must use List. However, I can see that there is a requirement of not inserting the duplicate, hence you are using a set. For that, what you can do is, you can use in operation in the loop and insert accordingly.

List<MyObject> data = [];

// you can add your object to the list with the check whether 
// it is already there
if(object in data){
  print('Already there');
}else{
  data.insert(index, object);
}

//print the data to check
print(data);

I hope this gives you some clarity, and get what you're desired to get.

Upvotes: 1

Related Questions