Tuesday, 30 August 2011

whai is set interface? java interview questions ...

 Answer :

  • Java collections Set interface is part of java.util package.
  • A set is a public interface that extends the collection interface 
  • It holds unique values(set does not contain duplicate elements).

It has two useful concrete classes that implements sets

  1. java.util.HashSet
   2.  java.util.TreeSet
                
  • Set value can get by Iterator interface.

Example:

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

public class SetExample {

    public static void main(String[] args) {

        // Set example with implement TreeSet
        Set<String> s=new TreeSet<String>();

        s.add("b");
        s.add("a");
        s.add("b");

        Iterator it=s.iterator();

        while(it.hasNext())
        {
          String value=(String)it.next();

          System.out.println("Value :"+value);
        }
    }
}


Output

Set Value :a
Set Value :b

  set ignore the duplicate value.

No comments: