Thursday, August 19, 2010

Set and Iterator

The Collections Framework in Java, which took shape with the release of JDK 1.2
and was expanded in 1.4 and again in Java 5, and yet again in Java 6, gives you lists,
sets, maps, and queues to satisfy most of your coding needs. They've been tried, tested,
and tweaked. Pick the best one for your job and you'll get—at the least—reasonable
performance. And when you need something a little more custom, the Collections
Framework in the java.util package is loaded with interfaces and utilities.


What are Sets - An unordered collections is called a set , you have probably learned some set theory in mathematics. If data structures is no longer responsible for remembering order of elements insertion , can  it give us better performance for some of its operations? It turns out to be true we will see it later. Lets check the operations on set first.

1) Adding element
2) Deleting element
3) Check if set contains a given object i.e containment testing
4) Listing all elements

One of the most important thing to remember about set is "Set's don't have duplicates values ,adding element in set that's already present is ignored".This is the most useful feature in many programming situations as well.
We could have used linked list to implement a set but all operations on set become slow due to linear search
through list we neglected it.Adding element in set requires check to make sure we don't add a duplicate

We have two data structures hash tables and trees. The standard java Library provides set implementation based on both data structures called hash Set and TreeSet. Both these data structures implement the Set interface.
 
                        
What is Iterator: It is used to visit all elements in set. A set iterator does not visit the elements in the order in which you inserted them. they are infact visited in order in which HashSet keeps them for rapid execution of its methods.


What is List Iterator : They use the next and hasnext methods to step through the set.

You might want to know then what is the difference between these two ?

List Iterator has an add method to add elements at the list iterator position but iterator interface has no such method.


Check Yourself - 1) Arrays and lists remember the order in which you added elements , set do not . Why would you want to use set instead of arrays or lists?


It is considered good way to store a references to a HashSet or TreeSet in a variable of type Set.

Set<String> names = new HashSet<String>();

Also methods that operate on set should specify parameters of type Set:
public static void print(Set<String> s)
Set Interface & the Map Interface are well designed and we should use them.

No comments:

Post a Comment