+ Reply to Thread
Results 1 to 2 of 2

Thread: Java Sets 1

  1. #1
    Join Date
    Mar 2008
    Posts
    7,145
    Rep Power
    86

    Java Sets 1

    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

    Code:
    TreeSet<Integer> v = new TreeSet<Integer>();
    This code creates a new TreeSet that will only store integers.

    Adding Items

    Code:
    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:

    Code:
    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.

    Code:
    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:

    Code:
    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.

  2. CODECALL Circuit advertisement
    Join Date
    Always
    Posts
    Many

     
  3. #2
    Jordan Guest

    Re: Java Sets 1

    As always, very well done. +rep

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Java Result Sets
    By chili5 in forum Java Tutorials
    Replies: 11
    Last Post: 01-07-2011, 05:03 PM
  2. Replies: 2
    Last Post: 04-27-2010, 08:04 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts