1

Accessing elements of a set.

If I have to access an element of a list , I can use the get() method . EX:- myList.get(1) would return the element at the 1st index.But the same seems invalid for sets. I am aware that set is an unordered collection. But does that mean that we cant access individual elements of a set?

  • As a side not, in order to get the first element, it would be `myList.get(0)`... now, in order to iterate over the set elements see: https://stackoverflow.com/questions/12455737/how-to-iterate-over-a-set-hashset-without-an-iterator If you have any specific doubt after reading that, update your question with the specific doubt/problem. – lealceldeiro Apr 21 '19 at 18:30
  • Possible duplicate of [How to Iterate over a Set/HashSet without an Iterator?](https://stackoverflow.com/questions/12455737/how-to-iterate-over-a-set-hashset-without-an-iterator) – lealceldeiro Apr 21 '19 at 18:31
  • We can, but in order decided by set's implementation. So unfortunately if you want to do it you would need to use iterator and iterate n times to get to n-th element. You can also copy current elements to list and then take them from it based on their index, but if set will change, list will not. – Pshemo Apr 21 '19 at 18:32

1 Answers1

1

LIST class provides you the get method, but there is no get method in SET. As SET is an unordered collection, it is not certain to get the correct element in correct index.

The solution to this problem is, Cast the SET to LIST.

SET<String> str = new Set<String>();
str.add('4');
str.add('1');
str.add('2');
str.add('3');


string f = (new list<string>(str) )[0];
string s = (new list<string>(str) )[1];

You can get the element by index by this way.

Noor A Shuvo
  • 2,639
  • 3
  • 23
  • 48