The Set

The Set


Posted in : Core Java Posted on : October 20, 2010 at 4:12 PM Comments : [ 0 ]

This section contains the detail about the Set in java.

The Set

The Set Collection can't contain duplicate elements same as set in math. It can implement only methods inherited from collection. Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.

The following table contains the methods declared by set :

    Methods         Description     
add( )  Adds an object to the collection
clear( )  Removes all objects from the collection
contains( )  Returns true if a specified object is an element within the collection
isEmpty( ) Returns true if the collection has no elements
iterator( )  Returns an Iterator object for the collection which may be used to retrieve an object
remove( )  Removes a specified object from the collection
size( )  Returns the number of elements in the collection.

Example :


import java.util.*;

public class SetExample {

public static void main(String args[]) {
	int count[] = { 3, 12, 21, 30, 48, 84 };
	Set set = new HashSet();
	try {
	for (int i = 0; i < 3; i++) {
		set.add(count[i]);
	}
	System.out.println(set);

	TreeSet sortedSet = new TreeSet(set);
	System.out.println("The sorted list is:");
	System.out.println(sortedSet);

	System.out.println("First element in the set: "
			+ (Integer) sortedSet.first());
	System.out.println("Last element in the set: "
			+ (Integer) sortedSet.last());
	} catch (Exception e) {
   }
  }

}

Output :

C:\Program Files\Java\jdk1.6.0_18\bin>javac SetExample.java

C:\Program Files\Java\jdk1.6.0_18\bin>java SetExample
[3, 21, 12]
The sorted list is:
[3, 12, 21]
First element in the set: 3
Last element in the set: 21

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics