Set Interface in Java

Set Interface in Java


Posted in : Java Posted on : November 24, 2010 at 4:53 PM Comments : [ 0 ]

The Set interface extends the Collection interface. A Set is a Collection that cannot contain duplicate elements.

Set Interface in Java:-

The Set interface extends the Collection interface. A Set is a Collection that cannot contain duplicate elements. Not only must these elements be unique, but while they are in the set, each element must not be modified. It permits a single element to be null. The Set interface contains only methods inherited from Collection.

The Collection Framework provides two concrete set implementations: 

1- HashSet

2- TreeSet

The HashSet represents a set backed by a hash table providing constant lookup−time access to unordered elements. 

The TreeSet maintains its elements in an ordered fashion within a balanced tree.

The Set interface contains only methods inherited from Collection interface, these are shown  given below:

  • add( )
  • clear( )
  • contains( )
  • isEmpty( )
  • iterator( )
  • remove( )
  • size( )
The Example for the Set interface which impliments the TreeSet class ia as-

SetDemo.java

package devmanuals.com;

import java.util.*;

public class SetDemo {
	public static void main(String[] args) {

		Set st = new TreeSet();

		st.add("Gyan");
		st.add("Rohit");
		st.add("Anand");
		st.add("Arunesh");

		Iterator itr = st.iterator();

		while (itr.hasNext()) {
			String str = (String) itr.next();

			System.out.println("Name :" + str);
		}
	}

}

Output:-

Name :Anand

Name :Arunesh

Name :Gyan

Name :Rohit

Download The Code:

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics