HashSet class


Hierarchy of HashSet class:


 

 public class HashSet<E>
        extends AbstractSet<E>
           implements Set<E>, Cloneable, java.io.Serializable

Key points:

  • HashSet is sub class of AbstractSet class.
  • Underlying data structure of HashSet is HashTable.
  • HashSet implements Serializable and Cloneable interfaces
  • HashSet does not allow duplicate elements.
  • Insertion order is not preserved. No order(Based on hashcode of objects)



Constructors of HashSet:

1.HashSet( )
  • Creates an empty HashSet object with default initial capacity 16.  Fill ratio or load factor 0.75
2.HashSet(Collection obj)
  • This constructor initializes the hash set by using the elements of the collection obj.
3.HashSet(int capacity)
    • Creates an empty HashSet object with given capacity.
      4.HashSet(int capacity, float fillRatio)
      • This constructor initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments (fill ratio 0.1 to 1.0)

      Reverse words in a String

      1. Java Interview Program to Reverse words in a string


      1. package com.instaceofjava;
      2.  
      3. public class ReverseString {
      4.  
      5. public static void main(String[] args) {
      6.  
      7. String strng= "Instance of Java ";
      8.  
      9. String str[] =strng.split(" ");
      10.  
      11. String result="";
      12.  
      13. for(int i=str.length()-1;i>=0;i--){
      14.  
      15. result += str[i]+" ";
      16.  
      17. }
      18.  
      19. System.out.println(result );
      20. }
      21. }
      Output:

      1. Java of Instance



      2. Java Interview Program to Reverse words in a string


      1. package com.instaceofjava;
      2.  
      3. public class ReverseString {
      4.  
      5. public static void main(String[] args) {
      6.  
      7. String strng= "Instance of Java ";
      8.  
      9. StringBuilder sb = new StringBuilder(strng.length() + 1);
      10.  
      11.   String[] words = strng.split(" ");
      12.  
      13.   for (int i = words.length - 1; i >= 0; i--) {
      14.          sb.append(words[i]).append(' ');
      15.    }
      16.     
      17.     sb.setLength(sb.length() - 1); 
      18.  
      19.    String result= sb.toString();  
      20.  
      21.     System.out.println(result);

      22. }
      23. }
      Output:

      1. Java of Instance

      Select Menu