Jump to content

Recent Status Updates

  • Photo
      15 Nov

    Hi, I am final year Interior Design Student from University of Huddersfield. I am currently working on my final major project which is going to be linked to coding. I was hoping that you could help me with my research. I have prepared a short survey, it would be a massive help if you could fill it in for me. It takes less than 2 minutes to complete, I promise. Here is the link: https://www.surveymonkey.com/s/73XLJKK Thank you so much in advance!

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

Powered by binpress