NSMutableArray makes awesome Cocoa stacks and queues

A difference between Java and Objective-C/Cocoa? Java has ConcurrentLinkedQueue, PriorityBlockingQueue, ArrayBlockingQueue, blah blah blah.

Objective-C/Cocoa(or Foundation) has NSMutableArray. NSMutableArray has some nice instance methods that make it _extremely_ easy to build a queue, stack, priority queue (synchronized or otherwise) without loading up the API with a billion separate classes.

Need a stack?

-(void) push:(id) item {
[list addObject:item] // where list is the actual array in your stack
count++;
}

-(id) pop {
id r = [list lastObject];
[list removeLastObject];
count--;
return r;
}


How about a queue?


-(void) enqueue:(id) item {
[list insertObject:item atIndex:0];
count++;
}

-(id) dequeue {
id r = [list lastObject];
[list removeLastObject];
count--;
return r;
}


Priority queueing and/or synchronization for thread-safety will be left as an exercise for the reader. Man, I've always wanted to say that... :)