Jump to content




Recent Topics

Recent Status Updates

View All Updates

Developed by TechBiz Xccelerator
Photo
- - - - -

Java Sets 1


  • Please log in to reply
1 reply to this topic

#1 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3,033 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 01 November 2009 - 06:01 PM

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

TreeSet<Integer> v = new TreeSet<Integer>();

This code creates a new TreeSet that will only store integers.

Adding Items

v.add(5);
v.add(3);
v.add(2);
v.add(4);
v.add(5);

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.


Add All

You can add all elements in a collection to a set using the addAll method.

Example:

ArrayList<Integer> nums = new ArrayList();
for (int i=0;i<5;i++) nums.add(i);
v.addAll(nums);

Iterators

An iterator allows you to iterate and process the items in a set.

Iterator<Integer> it = v.iterator();

while (it.hasNext()) {
	System.out.println(it.next());
}

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.

Output:

2
3
4
5


Notice how the output is in sorted order? This is because we used a TreeSet which implements the SortedSet interface.

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:

v.clear();
System.out.println(v.size());

This is useful in contest programming when you want to reset the variables for the next set of input.

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.
  • 1

#2 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 02 November 2009 - 06:09 AM

As always, very well done. +rep
  • 0




Powered by binpress