Java Using Sets
A set is a container that doesn't allow duplicate values.
In Java, there is three implementations of the set: TreeSet, HashSet, LinkedHashSet.
The difference is the TreeSet maintains items in sorted order, the HashSet doesn't maintain the items in any specific order. The LinkedHashSet maintains items in insertion order.All three Set classes implement the Set interface so it is easy to change the type of set used.
Creating a Set
This code creates a new TreeSet that will only store integers.Code:TreeSet<Integer> v = new TreeSet<Integer>();
Adding Items
The add method adds an item to the set. After executing the above code the number of items is 4. The 5 is only added once. After executing v.add(5) a second time nothing happens.Code:v.add(5); v.add(3); v.add(2); v.add(4); v.add(5);
Add All
You can add all elements in a collection to a set using the addAll method.
Example:
IteratorsCode:ArrayList<Integer> nums = new ArrayList(); for (int i=0;i<5;i++) nums.add(i); v.addAll(nums);
An iterator allows you to iterate and process the items in a set.
The next method moves a pointer to the next element in the set and outputs the previous item. The hasNext method will return false when the pointer is pointing after the last item.Code:Iterator<Integer> it = v.iterator(); while (it.hasNext()) { System.out.println(it.next()); }
Output:
Notice how the output is in sorted order? This is because we used a TreeSet which implements the SortedSet interface.2
3
4
5
Removing All Items
This is a simply matter of calling the clear method. It removes all items in the set. Then the size will be set to zero.
Example:
This is useful in contest programming when you want to reset the variables for the next set of input.Code:v.clear(); System.out.println(v.size());
This is a quick introduction to sets. In the next tutorial we will look at the other methods in the set interface and converting between sets.
As always, very well done. +rep
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks