Jump to content

Check out our Community Blogs

Recent Status Updates

  • Photo
      30 Mar
    wim DC

    At last I finally updated my profile again: Learning python. Even though I use it every day professionally now, I rather have it as learning for now :)

View All Updates

Developed by TechBiz Xccelerator
- - - - -

Java Sets 1

  • Please log in to reply
1 reply to this topic

#1 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


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.


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


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

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

while (it.hasNext()) {

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.



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.



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

Posted 02 November 2009 - 06:09 AM

As always, very well done. +rep
  • 0