Top 35+ Java Set Interface Interview Questions Answers for 0 to 5 years Experience

Java Set Interface Interview Questions with Answers

In the previous article, I wrote about Top 35 Java List Interface Interview Questions Answers for 0 to 5 years Experience In this article, I am going to share Top 35+ Java Set Interface Interview Questions Answers for 0 to 5 years Experience frequently asked on Interview. You can expect many questions from this topic in the interview.

Q1. What is Set collection in java?
Ans: Set Interface in Java which extends the collection. Set is a collection of the element in java.

Q2. What are methods Set interface contains?
Ans: The Methods of the set interface are as follows:

  • int size(): This method is used to get the number of elements in the Set.
  • boolean isEmpty(): It is used to check if Set is empty or not.
  • boolean contains(Object o): Returns true if this set contains the specified element.
  • Iterator iterator(): This method returns an iterator over the elements in this set. The elements are returned in no particular order.
  • Object[] toArray(): it returns an array containing all of the elements in this set. If this set makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.
  • boolean add(E e): This method return adds the specified element to this set if it is not already present (optional operation).
  • boolean remove(Object o): It removes the specified element from this set if it is present (optional operation).
  • boolean removeAll(Collection c): This method removes from this set all of its elements that are contained in the specified collection (optional operation).
  • boolean retainAll(Collection c): it retains only the elements in this set that are contained in the specified collection (optional operation).
  • void clear(): This method removes all the elements from the set.

Q3. What is HashSet in java?
Ans: HashSet is a collection class and found under java.util package.

Q4. Is it possible to store a duplicate element in HashSet?
Ans:
No, it is not possible

Q5. How the elements are stored in the HashSet?
Ans: In HashSet insertion, an order is not preserved. It means the element stored in an unordered way to the Set.

Q6. What happens if a duplicate element is stored in the HashSet?
Ans:
If any duplicate element or object is entered then it returns false.

Q7. In what based the elements are entered in the HashSet?
Ans:
Insertion of the object will be based on hashcode.

Q8. HashSet stores heterogeneous or homogenous type of element in it?
Ans: HashSet stores heterogeneous type of element to it.

Q9. Is it possible to enter the null element in the HashSet?
Ans: Yes. It is possible.

Q10. What are the interfaces implemented by HashSet?
Ans: It implements Serializable and cloneable interface.

Q11. What are the constructors of the HashSet?
Ans: The constructor are as follows:

  • HashSet h = new HashSet();
  • HashSet h = new HashSet (int intialcapacity, int 1000); load factor is 0.75 only.
  • HashSet h = new HashSet( int initial capacity, float load factor);
  • HashSet h = new HashSet( Collection obj);

Q12. What is the default initial capacity of the HashSet and what do you understand by Fill ration of it?
Ans: Default initial capacity of HashSet is 16 and fill ration of HashSet is 0.75. Fill ration also called a load factor. Here, after filling the 75 percent of the space of 16 then new object space is created to store.

Q13. Write a small program to add the element in the HashSet and also retrieve it?
Ans:

import java.util.*;  
class XadminHS{  
 public static void main(String args[]){  
  //Creating HashSet and adding elements  
    HashSet<String> xAdminHS=new HashSet();  
           xAdminHS.add("XadminOne");    
           xAdminHS.add("XadminTwo");    
           xAdminHS.add("XadminThree");   
           xAdminHS.add("XadminFour");  
           xAdminHS.add("XadminFive");  
           Iterator<String> i=xAdminHS.iterator();  
           while(i.hasNext())  
           {  
           System.out.println(i.next());  
           }  
 }  
}

Output:
XadminFive
XadminFour
XadminOne
XadminThree
XadminTwo

Q14. What is LinkedHashSet and the properties of HashSet in Java?
Ans: LinkedHashSet is an ordered version of the HashSet.
The properties of LinkedHashSet in java are listed below:

  • In LinkedHashSet no duplicate element is allowed to store.
  • In LinkedHashSet insertion order is in an ordered way.
  • Underline DataStructure is HashTable and Linked list.

Q15. LinkedList is synchronized or Non-synchronized?
Ans: Java LinkedHashSet class is non-synchronized.

Q16. Difference between HashSet and LinkedHashSet
Ans:

HashSet

LinkedHashSet

Underline data structure is a hashtable UnderLine data structure is hashtable and linked list
Element stored in an unordered way Element is an ordered way
HashSet comes in 1.2 version of java LinkedHashSet comes in 1.4 version of java

Q17. Where to use LinkedHashSet?
Ans:
Linked HashSet has used in cache-based application because duplication of an element to store is not allowed and data stored in an ordered way.

Q18. What is the constructor of the LinkedHashSet?
Ans: Constructor for LinkedHashSet is as follows:

  • LinkedHashSet(int capacity): It is used to initialize the capacity of the LinkedHashSet to the given integer value capacity
  • LinkedHashSet(int capacity, float fill Ratio): It is used to initialize both the capacity and the fill ratio (also called load capacity) of the hash set from its argument.

Q19. Write and sample code to insert and retrieve the elements in LinkedHashSet?
Ans:

import java.util.*;  
class Xadmin{  
 public static void main(String args[]){  
 //Creating HashSet and adding elements  
        LinkedHashSet<String> xAdminSet=new LinkedHashSet();  
               xAdminSet.add("XAdminOne");    
               xAdminSet.add("XadminTwo");    
               xAdminSet.add("XadminThree");   
               xAdminSet.add("XadminFour");  
               xAdminSet.add("XadminFive");  
               Iterator<String> i=xAdminSet.iterator();  
               while(i.hasNext())  
               {  
               System.out.println(i.next());  
               }  
 }  
}  

Output:

XAdminOne
XAdminTwo
XAdminThree
XAdminFour
XadminFive
As, looking at the output, here you can notice that the elements iterate in insertion order.

Q20. What is the SortedSet in Java?
Ans:
The SortedSet interface extends Set and declares the behavior of a set sorted in ascending order.

Q21. Is it possible to store a duplicate element in the SortedSet?
Ans: No, not possible.

Q22. Is it possible to store the null element in the SortedSet?
Ans: No, null is not allowed to store.
A NullPointerException is thrown if an attempt is made to use a null object.

Q23. In what way elements are stored in SortedSet.
Ans:
In SortedSet, element are stored in ordered way. Default storage is in ascending order.

Q24. Tell the different methods of the SoetedSet and explain their functionality?
Ans: Method for SortedSet in java is listed below:

  • Comparator comparator(): This return the invoking sorted set’s comparator. If the natural ordering is used for this set, null is returned.
  • The object first(): it will return the first element of the sorted set.
  •  SortedSet headSet(Object end): This method returns a SortedSet containing those elements less than end that are contained in the invoking sorted set. Elements in the returned sorted set are also referenced by the invoking sorted set.

  • Object last( ): it returns the last element in the invoking sorted set.

Q25. What are TreeSet and it properties in Java?
Ans: The main point regarding the TreeSet in java are listed below:

  • Underlying Data Structure is a balanced tree.
  • Duplicates element are allowed.
  • Insertion order is done according to the sorting order.
  • Only a homogenous element is allowed to store.

Q26. What is the constructor of the TreeSet?
Ans: Constructor of TreeSet are as follows:

  • TreeSet ts = new TreeSet(); This create the empty TreeSet object. The element will be inserted according to the default sorting order.
  • TreeSet ts = new TreeSet(Comparator c); This is use for coustomized sorting order.
  • TreeSet ts = new TreeSet(Collection c); This is used to create the object of the TreeSet and store the entire collection in that object.
  • TreeSet ts = new TreeSet(SortedSet s); Creates the TreeSet object and insert SortedSet obj in it.

Q27. Explain the concept of Null acceptance in TreeSet?
Ans:
Concept of Null acceptance in TreeSet:

  • According to default object creation by using TreeSet ts = new TreeSet();
  • For the empty TreeSet as the first element null insertion is possible. But after inserting that null, if we are trying to insert any another element then we will get NullPointerException.
  • For non-empty TreeSet if we are trying to insert null then we will get NullPointerException.

Q28. The output of the sample program?
Ans:

 class Xadmin
{
Public static void main(String args[]);
{
TreeSet t = new TreeSet();
t.add(new StringBuffer(“A”);
t.add(new StringBuffer(“Z”);
t.add(new StringBuffer(“L”);
t.add(new StringBuffer(“B”);

}
}

Output:
Runtime error: ClassCastException
In default natural sorting order
An object should be Homogenous and comparable
Here, StringBuffer is not comparable. So RunTimeException
StringBuffer is not implemented comparable.

Q29. What do you know about Comparable(I) Interface?
Ans:
It is defined inside Java.lang.package. Only one method compareTo() present inside this interface. i.e, Public int compareTo (Object obj1)

Q30. Explain the return value of obj1.compareTo(obj2) method?
Ans:
obj1.compareTo(obj2):

  • This method returns negative if obj1 has to come before obj2.
  • This method returns positive if obj1 has to come after obj2.
  • This method returns zero if obj1 equal to obj2.

System.out.println(“A” compareTo(“Z”)); -> negative
System.out.println(“Z” compareTo(“B”)); -> postive
System.out.println(“A” compareTo(“A”)); -> zero
System,out.println(“A” compareTo(null));-> RunTimeException: NullPointerException

Q31. What is Comparator interface?
Ans:
Comparator (I) is used for customized sorting. This interface comes under Java. util package.

Q32 What are two methods of Comparator interface?
Ans:
This contains compare() and equals() methods. Prototype of compare() and equals() method are:

  • Public int compare(Object obj1, Object obj2): This method returns negative if obj1 has to come before obj2. Returns positive, if obj1 has to come after obj2. Returns zero if equal.
  • Public equal(): Implementation of the equal method is optional. Because the equal method is of an object class, so Dummy implementation is already present.

Q33. Is it possible to change the storing order of the TreeSet and if yes? explain the process?
Ans:
As we know, TreeSet store the object or element in sorting order. As default sorting order is in ascending order.
If we want to store in descending order then we have implemented our own comparator.

Class MyComparator implements Compartor
{
Public int compare( Object obj1, Object obj2)
{
Integer i1 = (Integer) obj1;
Interger 12 = (Interger) obj2;
if(i1<i2)
return +1;
else if(i1>i2)
return -1;
else
return 0;
}
}
class Xadmin
{
public static void main(String args[])
{
TreeSet t = new TreeSet( new MyComparator());
t.add(10);
t.add(0);
t.add(15);
t.add(20);
t.add(20);
System.out.println(t);
}
}

Output: [20,15,10,0]

Q34. Difference between Comparable and comparator
Ans:

Comparator

Comparable

Pre-defined comparable classes[eg. String] Pre-defined Non- comparable class [eg. String buffer]
This is used for default natural sorting This is used for Coustamized sorting order.
This comes under java.lang package This comes under java.util package
One method is present i.e compareTo() Two methods are present compare and equal method

Q35. What is the important point we should keep in mind if we are storing the object in the TreeSet?
Ans: if we are storing the object in the TreeSet then
the object should be homogenous and comparable. Otherwise, we will get runtime exception saying ClassCastException.

Q36. What is the advantage of storing the object in the TreeSet with custom sorting process?
Ans:
If we are defining our own sorting by comparator then objects need not be homogenous and comparable. We can insert heterogeneous and non-comparable objects also.

That’s all about Set Interface interview questions with answers from Core Java Interviews. I have covered almost everything as per my knowledge for both freshers and experienced with 0 to 5  years, so prepare well for the Java interview Questions, I suggest you take a look at more Java Programming Interview Questions with answers on different topics of the core java posted in this xadmin website. Keep Learning!  All the Best!