Tuesday, 3 November 2015

How to work with Subsets of TreeSet



Since a TreeSet is ordered ,a subset of the tree set is also ordered. TreeSet class provides several methods for working with these subsets.The two subsets among them are headSet() and tailSet():

    public SortedSet headSet(Object toElement)  
    public SortedSet tailSet(Object toElement)  

The third method subSet() provides the endpoints:

    public SortedSet subSet(Object fromElement,Object toElement)  

All of these methods will give you a view into the underlying tree such that changes to that view are reflected in the set from which the view came from .In other words, if you remove something from the subset, it's gone. In addition, if you try to add something to the subtree, it must fit within your view of the tree. And if you add something to the original view, the subset will be altered too.

In headSet method, fromElement is not included as a part of resultant set whereas in case of tailSet,fromElement is included.

If you want to include the fromElement in the subset of headSet, you must do something like this

   SortedSet headSet = set.headSet(toElement+"\0");  

and if you don't want to include the fromElement in subset of tailSet:

   SortedSet tailSet = set.tailSet(fromElement+"\0");  

To get a set that includes both the ends, use:

   SortedSet set = set.subSet(fromElement,toElement+"\0");  

Or, for a set that includes neither end, use:

   SortedSet set = set.subSet(fromElement+"\0",toElement);  

Here are some few examples which will help to understand this better.
For example, you have a treeSet ("John","Mary","Dean","Sam","Lillith").as we know tree is ordered set.All the element will stored in sorted order.

  • tailSet("John") :- [John,Lillith,Mary,Sam]
  • headSet("John") :- [Dean]
  • headSet("John\0") :- [Dean,John]
  • tailSet("John\0") :- [Lillith,Mary,Sam]
  • subSet("John","Mary\0") :- [John,Lillith,Mary]
  • subSet("John","John\0") :- [John]
  • subSet("John","John") :- []


Enjoy Reading.


What is UnsupportedOperationException?


UnsupportedOperationException:- The UnsupportedOperationException is thrown when you try to call a collections-related method on an instance of a collection's interface that does not provide a complete implementation of that interface.If a collection is a fixed-size or read-only collection, you can''t add or remove elements from it.Trying to perform such an operation causes this exception to be thrown.


Sample Program:-


import java.util.Arrays;  
 import java.util.List;  
 public class UnsupportedOperationExceptionExample {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           String[] s = { "a", "b" };  
           List l1 = Arrays.asList(s);  
           l1.add("c");  
      }  
 }  

Output:-


 Exception in thread "main" java.lang.UnsupportedOperationException  
      at java.util.AbstractList.add(Unknown Source)  
      at java.util.AbstractList.add(Unknown Source)  
      at ConcurrentModificationExceptionExample.main(ConcurrentModificationExceptionExample.java:20) 

In above program, Arrays.asList() returns a fixed-length collection, so you can't add anything without causing the exception to be thrown.


Enjoy Reading.

What is ConcurrentModificationException?


ConcurrentModificationException:- The ConcurrentModificationException has to do with the fail-fast nature of the collection iterators.If an underlying collection is modified outside the remove() method of the iterator while you are iterating through its elements, this will be detected upon the next access and a ConcurrentModificationException will be thrown, thereby causing the iteration to stop.


For example:-


import java.util.ArrayList;  
 import java.util.Iterator;  
 import java.util.List;  
 public class ConcurrentModificationExceptionExample {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           List<String> l=new ArrayList<String>();  
           l.add("Sub");  
           l.add("Mul");  
           l.add("Div");  
           Iterator<String> itr=l.iterator();  
           while(itr.hasNext())  
           {  
                System.out.println(itr.next());  
                l.add("Add");  
           }  
      }  
 }  

Output:-
Sub  
 Exception in thread "main" java.util.ConcurrentModificationException  
      at java.util.AbstractList$Itr.checkForComodification(Unknown Source)  
      at java.util.AbstractList$Itr.next(Unknown Source)  
      at ConcurrentModificationExceptionExample.main(ConcurrentModificationExceptionExample.java:20)  


The above program starts by walking the elements of an iterator but adds an element after printing the first one. As this modifies the underlying collection, the iterator is immediately invalidated such that second call to next() fails.

ConcurrentModificationException is a run-time exception.you don't have to place all your iterating code in try-catch block.

The methods which can cause modification to the Collection interface are :- add(), addAll(), clear(), remove(), removeAll(), retainAll().


Enjoy Reading :)

How to find out time taken by a method for execution without using any profiling tool


In order to check the performance of any method,we can read the system time just before the method is invoked and immediately after method returns.Then we can take the time difference, which will give us the time taken by a method for execution.

For example:-

                long start = System.currentTimeMillis();
                method();
                long end = System.currentTimeMillis();

System.out.println("Time taken for execution is :" + (end - start));

Sample Program:-


 /**  
  * @author Dixit  
  *   
  */  
 public class ArmstrongProgram {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           long start = System.currentTimeMillis();  
           checkArmsStrongNumber();  
           long end = System.currentTimeMillis();  
           System.out.println("Time taken for execution is :" + (end - start)  
                     + " milliseconds");  
      }  
      private static void checkArmsStrongNumber() {  
           int num = 153;  
           int n = num;  
           int check = 0, remainder;  
           while (num > 0) {  
                remainder = num % 10;  
                check = check + (int) Math.pow(remainder, 3);  
                num = num / 10;  
           }  
           if (check == n)  
                System.out.println(n + " is an Armstrong Number");  
           else  
                System.out.println(n + " is not a Armstrong Number");  
      }  
 }  


Output  
 153 is an Armstrong Number  
 Time taken for execution is :1 milliseconds  


Enjoy Reading.

What is Constructors,Constructor Overloading and Copy-Constructor?



Constructors: The main purpose of having constructors is to create an instance of a class.They are invoked while creating an instance of a class.

The silent features of Java constructors:

  • Constructors can be public, private or protected.
  • If a constructor with arguments has been defined in a class, you can no longer use a default no-argument constructor. you have to write one.
  • They are called only once when the class is being instantiated.
  • They must have the same name as class itself.
  • They do not return a value and you don not have to specify the keyword void.
  • If you do not create a constructor for the class, Java helps you by using a so called default no-argument constructor.

 public class SampleProgram {  
      String name;  
      // This is the the constructor  
      public SampleProgram(String name) {  
           this.name = name;  
      }  
      public void display() {  
           System.out.println("Name is :" + name);  
      }  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           SampleProgram s = new SampleProgram("Ashish");  
           s.display();  
      }  
 }  


Constructor Overloading:- In constructor overloading ,we pass different number and type of variable as arguments all of which are private variables of the class.

 public class SampleProgram {  
      String name;  
      public SampleProgram() {  
           this.name = "Manish";  
      }  
      // This is the the constructor  
      SampleProgram(String name) {  
           this.name = name;  
      }  
      public void display() {  
           System.out.println("Name is :" + name);  
      }  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           SampleProgram s = new SampleProgram("Ashish");  
           s.display();  
           SampleProgram s1=new SampleProgram();  
           s1.display();  
      }  
 }  


Copy Constructor:- A copy constructor is a type of constructor which constructs the object of the class from another object of the same class.The copy constructor accepts a refernce to tis own class as parameter.

Note:- Java does not support Copy Constructor.So don't get confused.It is supported in C++.


Enjoy Reading:)




Monday, 2 November 2015

Java program to generate Harmonic Series


Write a program to generate Harmonic Series.

Input:- 5

Output:- 1 + 1/2 + 1/3 + 1/4 + 1/5 = 2.28 (Approximately)

Sample Program:-

 /**  
  * @author Dixit  
  *   
  */  
 public class HarmonicSeries {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           int num = 5;  
           double result = 0.0;  
           while (num > 0) {  
                result = result + (double) 1 / num;  
                num--;  
           }  
           System.out.println("Output is " + result);  
      }  
 }  

Output  
 Output is 2.283333333333333  

Enjoy Programming.

Java program to find whether given number is Armstrong or not


Write a program to find whether given number is Armstrong or not.

Input:- 153

Output:- 1^3 + 5^3 + 3^3 = 153, so it is Armstrong no.


Sample Program:-

 /**  
  * @author Dixit  
  *   
  */  
 public class ArmstrongProgram {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           int num = 153;  
           int n = num;   
           int check = 0, remainder;  
           while (num > 0) {  
                remainder = num % 10;  
                check = check + (int) Math.pow(remainder, 3);  
                num = num / 10;  
           }  
           if (check == n)  
                System.out.println(n + " is an Armstrong Number");  
           else  
                System.out.println(n + " is not a Armstrong Number");  
      }  
 }  

 Output  
 153 is an Armstrong Number  

Enjoy Programming.