What is Set interface

What is Set interface

Answer: Below are details:

  • Set is an interface which extends Collection Interface
  • It can not contain duplicate elements
  • Set interface can contains only methods and that is inherited from Collection also put restriction that duplicate elements not allowed
  • There are three general purpose of Set implementations are available in Java i.e. TreeeSet, HashSet and LinkedHashSet
  • This interface adds a contract on behavior of equals and hashCode operations from Object class that allow Set instances to be compared importantly if their implementation types are different.
  • Also any two Set object instances is equal if they have same elements

Below is example of Set interface:

package com.javahonk.setTest;

import java.util.HashSet;
import java.util.Set;

public class SetTest {

	public static void main(String[] args) {

	Set<String> set = new HashSet<String>();

	set.add("I");
	set.add("I");
	set.add("am");
	set.add("am");
	set.add("Java");
	set.add("Set");		

	//Duplicate value won't be added
	for (String string : set) {
		System.out.println(string);
	}

	}

}

 

Output:

What is Set interface

Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *