Sunday, 1 November 2015

How to create a HashSet



The HashSet classes provides four constructors .The first three constructors crate empty sets of varying sizes:

   public HashSet ()  
   public HashSet (int initialCapacity)  
   public HashSet (int initialCapacity, int loadFactor)  

If initialCapacity is not specified, then initial set size for storing elements will be the default size of a HashMap, which is either 11 or 101 depending upon the Java version you are using. When the set capacity reaches full and a new element is added, the internal structure will double in size before adding the new element. you can also provide custom load factor in the constructor.

The fourth constructor acts as a copy constructor ,copying the elements from ine set into the newly created set:

   public HashSet (Collection c)  

You cannot provide a custom initial capacity or load factor. Instead, the internal map will be sized at twice the size of collection, or eleven if the collection is small(five or less elements),keeping the default load factor of 75%.

Note: If the original collection had duplicates ,only one of the duplicates will be in the final created set.

An easy way to initialize a set without manually adding each element is to create an array of the elements, create a List from that array with Arrays.asList(), then call this constructor with the list as the collection:

  String st[]={“a”,”b”,”c”,”d”,”e”};  
  Set set =new HashSet(Arrays.asList(str));  


Happy Learning J

How to create an ArrayList



There are 3 constructors to create an ArrayList. For the first two construtors, an empty array list is created. The initial capacity is 10 unless it is explicitly specified by using the second constructor. When that space becomes too small, the list will increase by half of its size.

    public ArrayList()  
    public ArrayList (int initialCapacity)  

Note:- Unlike Vector, you cannot specify a capacity increment. For Sun’s reference implementation, the formula to increase capacity is newCapacity=(oldCapacity*3)/2+1. If you happen to call the constructor with a negative initial capacity, an IllegalArgumentException will be thrown.
Another constructor is copy constructor, creating a new ArrayList from another collection:
    
  public ArrayList(Collection c)  

You can not provide a custom initial capacity .Instead, the internal array will be sized at 10% larger than the collection size.

One of the easy way of creating ArrayList is

 String str[] = {“a”,”b”,”c”,”d”,”e”};  
 List list=new ArrayList(Arrays.as List(str));  



Happy Learning J

How to fetch elements from HashSet



To fetch an elements of Hashset, you can call the iterator() method to get an Iterator:
    
   public Iterator iterator()  

Since the elements of hash set are unordered, the order of the elements returned has nothing to do with the order in which they were inserted or added. And as the capacity of the hash set changes, the elements may be reordered.

For example:-

 import java.util.Arrays;  
 import java.util.HashSet;  
 import java.util.Iterator;  
 import java.util.Set;  
 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class HashSetIteration {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           String str[] = { "a", "b", "c", "d", "e" };  
           Set<String> set = new HashSet<String>(Arrays.asList(str));  
           Iterator<String> itr = set.iterator();  
           while (itr.hasNext()) {  
                System.out.println(itr.next());  
           }  
      }  
 }  

 Output:  
 d  
 e  
 b  
 c  
 a  

Remember that order doesn’t matter as long as each element in the set is displayed.


Happy Reading .

How to remove elements from HashSet



There are four ways to remove elements from Hashset.

      1)      Removing All Elements

The Simplest removal method, clear(), clears all of the elements from the set:

    public void clear()  

While there is no return value, you may get an UnsupportedOperationException thrown when working with read-only set.

      2)      Removing Single Elements

To remove a single element, you can use remove() method

    public boolean remove(Object element)  

Determining whether the element is in the set is done via the equals method of the element. If the element is present, the element is removed from the set and true is returned. If not found, false is returned. If a set is read only, the removing an element will throw UnsupportedOperationException.

      3)      Removing Another Collection

The third way to remove element is removeAll():

    public boolean removeAll(Collection c)  

The removeAll() method takes a Collection as an argument and removes from the set all instance of each element in the Collection passed in.The Collection passed in can be a Set or some other Collection. For example:-

{“a”,”b”,”c”,”d”,”e”}

And the collection passed in is

{“b”,”c”,”e”}

The resulting set would be

{“a”,”d”}

removeAll() returns true if the underlying set changed, or false or UnsupportedOperationException.

     4)      Retaining Another Collection

The retainAll() method works like removeAll(),but in opposite direction:

   public boolean retainAll(Collection c)  

Only those elements within the collection argument are kept in the original set. Everything else is removed. For example:-

{“a”,”b”,”c”,”d”,”e”}

And the collection passed in is

{“b”,”c”,”e”}

The resulting set would be

{“b”,”c”,”e”}


Happy Reading.

How to add element in ArrayList



You can add either a single element or a group of elements to the list.

      1)      Adding Single Elements

There are two varieties of the add() method to add a single element to the list .

    public boolean add(Object element)  
    public boolean add(int index,Object element)  

When called with only an element argument, the element is added to the end of the list. When add() is called with the both element and index arguments, the element is added at the specific index and any elements after it are pushed forward in the list.

For example:-

 List list=new ArrayList();  
 list.add(“a”);  
 list.add(“b”);  
 list.add(“c”);  
 list.add(1,“d”);  

Note:- Like Array, the index used by a List starts at zero.

Since all lists are ordered, the elements are held in the order in which they are added.Unless and until ,you specify the position to add the element as in list.add(1,“d”).
      
      2)      Adding Another Collection

You can add a group of elements to a list from another collection with the addAll() method:

    public boolean addAll(Object element)  
    public boolean addAll(int index,Object element)  

Each elemtn in the collection passed in will be added to the current list via the equivalent of calling the add() method on each element. If an index is passed to the method call, elements are added starting at that position, moving existing elements down to fit in the new elements. Otherwise, they are added to the end.

Note:- In both the cases, if list is read only, then an UnsupportedOperationException will be thrown.


Happy Learning J

What is Function Overriding and Function Overloading in Java



Over-Riding:- An override is a type of function which occurs in a class which inherits from another class. An override function “replaces” a function inherited from the base class, but does so in such a way that it is called even when an instance of its class is pretending to be a different type through polymorphism.

In simple words, method in base class is overridden in child class. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type. The code snippet below should explain things better.

Sample Program:-

 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class SampleProgram {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           Car a = new Car();  
           Car b = new Porche();// Car reference ,but a Porche object  
           a.start();// Car version of start method called  
           b.start();// Porche version of start method called  
      }  
 }  
 class Car {  
      public void start() {  
           System.out.println("Generic method to start the car in Base class");  
      }  
 }  
 class Porche extends Car {  
      public void start() {  
           System.out.println("Porche method to start the car in child class");  
      }  
 }  

 Output  
 Generic method to start the car in Base class  
 Porche method to start the car in child class  

The rules for overriding are:-

                 -          The argument list must exactly match that of the overridden method. If they
                    don't match, you can end up with an overloaded method you didn't intend.

                 -          The return type must be the same as, or a subtype of, the return type declared
                    in the original overridden method in the superclass.

                 -          The access level can't be more restrictive than the overridden method's.

                 -          The access level CAN be less restrictive than that of the overridden method.

                 -          Instance methods can be overridden only if they are inherited by the subclass.
                   A subclass within the same package as the instance's superclass can override
                   any superclass method that is not marked private or final. A subclass in a
                   different package can override only those non-final methods marked public
                   or protected (since protected methods are inherited by the subclass).

                 -          The overriding method CAN throw any unchecked (runtime) exception,
                    regardless of whether the overridden method declares the exception.

                 -          The overriding method must NOT throw checked exceptions that are new
                    or broader than those declared by the overridden method. For example, a
                    method that declares a FileNotFoundException cannot be overridden by a
                    method that declares a SQLException, Exception, or any other non-runtime
                    exception unless it's a subclass of FileNotFoundException.

                 -          The overriding method can throw narrower or fewer exceptions. Just because
                    an overridden method "takes risks" doesn't mean that the overriding subclass'
                    exception takes the same risks. Bottom line: an overriding method doesn't
                    have to declare any exceptions that it will never throw, regardless of what the
                    overridden method declares.

                  -          You cannot override a method marked final.

                  -          You cannot override a method marked static.

                  -          If a method can't be inherited, you cannot override it.

Over-Loading:- Overloading is the action of defining multiple methods with the same name, but with different parameters. It is unrelated to either overriding or polymorphism. Functions in java could be overloaded by two mechanisms ideally:

-          Varying the number of arguments
-          Varying the Data type

The rules are simple:-

-          Overloaded methods MUST change the argument list.
-          Overloaded methods CAN change the return type.
-          Overloaded methods CAN change the access modifier.
-          Overloaded methods CAN declare new or broader checked exceptions.
-          A method can be overloaded in the same class or in a subclass. In other words,
                     if class A defines a doStuff(int i) method, the subclass B could define a
         doStuff(String s) method without overriding the superclass version that
                     takes an int. So two methods with the same name but in different classes
                     can still be considered overloaded, if the subclass inherits one version of the
                     method and then declares another overloaded version in its class definition.


Sample Program:-


 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class CalulateSum {  
      void sum(int a, int b) {  
           System.out.println("Integer Sum:" + (a + b));  
      }  
      void sum(double a, double b) {  
           System.out.println("Double Sum:" + (a + b));  
      }  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           CalulateSum calulateSum = new CalulateSum();  
           calulateSum.sum(3, 4);  
           calulateSum.sum(3.2, 4.8);  
      }  
 }  



 Output  
 Integer Sum:7  
 Double Sum:8.0  

Happy Learning :)

Monday, 12 October 2015

How to remove spaces from given string



Suppose you have a String str="hello my na me i s John". How will you remove the spaces between words.Its a very basic question asked in interview for freshers.

I have mentioned two ways to do the same problem one is using split function and another is using replace function.


Sample Program:-

/**  
  *   
  */  
 /**  
  * @author Dixit  
  *  
  */  
 public class RemoveSpaceInStrings {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           String str="hello my na me i s John";  
           removeSpaceWithSplitFunction(str);  
           removeSpcaseWithoutSplitFunction(str);  
      }  
      private static void removeSpcaseWithoutSplitFunction(String str) {  
            System.out.println("removeSpcaseWithoutSplitFunction:Resulting String is:-" +str.replace(" ", ""));  
      }  
      private static void removeSpaceWithSplitFunction(String str) {  
         String result = "";  
         String strArray[] = str.split(" ");  
         for (int i = 0; i < strArray.length; i++) {  
           result = result + strArray[i];  
         }  
         System.out.println("removeSpaceWithSplitFunction:Resulting String is:-" + result);  
      }  
 }  


 Output  
 removeSpaceWithSplitFunction:Resulting String is:-hellomynameisJohn  
 removeSpcaseWithoutSplitFunction:Resulting String is:-hellomynameisJohn


Enjoy Programming :)