Java set example

In this tutorial we will see how to use the Java Set interface . We will create an example to display the contents of the set collection.

Java set example

In this tutorial we will see how to use the Java Set interface . We will create an example to display the contents of the set collection.

Java set example

Java set example

In this section you will learn about set interface in java. In java set is a collection that cannot contain duplicate element. The set interface contains method that inherited from collection which does not allow you to add duplicate elements in the set. The set interface has method which are as follows :

  • add() : Which allow to add an object to the collection..
  • clear() : Remove all object from the collection.
  • size() : Return the size of element of collection.
  • isEmpty() : Return true if the collection has element.
  • iterator() : Return an iterator object which is used to retrieve element from collection.
  • contains() : Returns true if the element is from specified collection.

Example of java set interface.

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;


public class SetInterface {
	public static void main(String args[])
	{
		
		Set s=new TreeSet();
		s.add(10);
		s.add(30);
		s.add(98);
		s.add(80);
		s.add(10); //duplicate value 
		s.add(99);
		Iterator it=s.iterator();
		while(it.hasNext())
		{
			System.out.println(it.next());
		}
		 System.out.println("Size of Set is =  "+s.size());
		 System.out.println("set is empty = "+s.isEmpty());
	}
}

Description : In the above code creating a set interface reference and adding element to the collection. As we know set does not allow duplicate elements,  so after adding 10 again we have added 10 to the collection but it wont displayed the value 10 two times. and when we compile and execute the it will display the element in ascending order.

Output : After compiling and executing the program