Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Set interface in java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 477
    Comment on it

    Set Interface in java,
    It is the type of Collection and Its the subclass of Collection interface so that all methods Collection interface can also present in Set interface.
    The important feature of Set interface is that it doesnt allow duplicacy or we can say it doesnt contain duplicate elements.
    We know Set is an interface so In order to use it we need an implementation.
    We have many options in Java Collections API like


    Java.util.Hashset, Java.util.LinkedHashSet, java.util.TreeSet,andjava.util.EnumSet 

    They all are little different with each other.

    These are some methods of Set:

    add( ) : It adds element to the collection.
    clear( ): Removes or clear all elements or object from the collection
    isEmpty( ): It returns true If collection is empty and having size 0.
    iterator( ): It use for retrieving objects.
    remove( ): It removes particular object from collection.
    size( ): It returns the actual size of collection or number of elements in a collection.

    Here I am writing code to explain how to implement simple Set Collection.

     int arrayTest[] = {53,23,35,64,54,53}; 
     Set<Integer> setHashSet = new HashSet<Integer>(); 
     try{ 
        for(int i = 0; i<6; i++){ 
           setHashSet.add(arrayTest [i]); 
        } 
        System.out.println(setHashSet); 
    
        TreeSet setTreeSet = new TreeSet<Integer>( setHashSet); 
        System.out.println("Great. It is sorted : : ::  "); 
        System.out.println(setTreeSet); 
    
        System.out.println("My First number: "+ 
                          (Integer) setTreeSet.first()); 
        System.out.println("My last number: "+ 
                        (Integer) setTreeSet.last()); 
     } 
     catch(Exception e){} 
    
    } 
    } 
    Here is the output:
    [53,23,35,64,54] Great. It is sorted : : ::
    [23,35,53,54,64] My First numbers:23 My last number:64

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: