0

I am java programmer. There is concept of HashSet in Java that don't add duplicate elements in a Set. What is the similar concept in iPhone that do same ?

Please hint.

Thanks in advance.

N Sharma
  • 33,489
  • 95
  • 256
  • 444
  • Most collection classes of the Foundation framework are described in detail in the ["Collections Programming Topics"](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Collections/Collections.html) documentation. If order is relevant then you can use NS(Mutable)OrderedSet. – Martin R Aug 25 '14 at 11:57

3 Answers3

1

You can use NSSet in iOS. NSSet is a (unordered) collection of unique items. So, you can find the unique items in your array like so:

     NSSet *uniqueElements = [NSSet setWithArray:myArray];

    // iterate over the unique items
    for(id element in uniqueElements)
       {
          // do something
       }

NSSet most likely uses a hash algorithm to make insertion O(1) (compared to O(n^2) to check if each item is unique by iteration), but the Apple documentation does not make such a guarantee so you probably shouldn't count on that implementation detail.

If, for some reason you need to keep the unique items in a sorted (ordered) collection, you can turn the set back into an array with -[NSSet allObjects] and then sort the resulting array.

Utkarsha
  • 250
  • 2
  • 12
  • I want they should be in same order as I insert into it. Does NSSet will be helpful for that ? – N Sharma Aug 25 '14 at 11:52
  • If you want it to be in same order then use NSOrderedSet: It is the ordered collection of distinct objects. – Utkarsha Aug 25 '14 at 11:58
0

NSSet use the has of NSObject to make sure that there are not duplicates.

Or NSMutableSet if you need to add thing to the set.

rckoenes
  • 69,092
  • 8
  • 134
  • 166
0

HashSet is the Java implementation of a Hash Table. NSHashTable is, I believe, the Cocoa equivalent.

gandaliter
  • 9,863
  • 1
  • 16
  • 23