Monday, May 23, 2011

Why Marker Interface ?

he main purpose to have marker interfaces is to create special types in those cases where the types themselves have no behavior particular to them. If there is no behavior then why to have an interface? Because the implementer of the class might only need to flag that it belongs to that particular type and everything else is handled/done by some other unit - either internal to Java (as in the case of Java supplied standard marker interfaces) or an app specific external unit.

Let's understand this by two examples - one in which we will discuss the purpose of a standard Java interface (Cloneable) and then another user-created marker interface.


When JVM sees a clone() method being invoked on an object, it first verifies if the underlying class has implemented the 'Cloneable' interface or not. If not, then it throws the exception CloneNotSupportedException
Assuming the underlying class has implemented the 'Cloneable' interface, JVM does some internal work (maybe by calling some method) to facilitate the cloning operation.
So, effectively marker interfaces kind of send out a signal to the corresponding external/internal entity (JVM in case of Cloneable) for them to arrange for the necessary functionality. 

public Object clone() throws CloneNotSupportedException {

 if (this implements Cloneable)

     return nativeCloneImpl();

 else

     throw new CloneNotSupportedException();

}
 
Can anyone tell why and when do we get 'CloneNotSupportedException' exception at compile-time itself? Well... that's no trick. If you see the signature of the 'Object.clone()' method carefully, you will see a throws clause associated with it. I'm sure how can you get rid of it: (i) by wrapping the clone-invocation code within appropriate try-catch (ii) throwing the CloneNotSupportedException from the calling method.

What purpose does a user-defined marker interface serve? It can well serve the same purpose as by any standard marker interface, but in that case the container (the module controlling the execution of the app) has to take the onus of making sure that whenever a class implements that interface it does the required work to support the underlying behavior - the way JVM does for Cloneable or any other standard marker interface for that matter.


user-defined marker interface in Java:-
to be continued........ 



Wednesday, April 27, 2011

DB Indexes

Q. What's DB indexes ?
A. basically used to sort data in a table.
There are basically 2 types of DB indexes:- Clustered and non-clusterd

Q. What's Mean By Cluster?
A. Oracle cluster supply an optional way of storing table data. In a cluster a group of tables share the same data blocks. The tables are grouped together because they share identical columns and are often used together. For example, the employee and department table use the depth no column. When you cluster the employee and department tables Oracle Database physically stores all rows for each department from both the employee and department tables in the same data blocks.
A cluster is used in database so that to keep all the rows of all data tables together and they can easily be accessed by the help of shared cluster key.

Because clusters store relevant rows of dissimilar tables together in the one data blocks, correctly used clusters offer two primary benefits:
■ Disk I/O is condensed and access time improves for joins of clustered tables.
■ The cluster key is the column, or collection of columns, that the clustered tables have
in same. You identify the columns of the cluster key when creating the cluster.
You next specify the same columns when creating every table added to the cluster. Each cluster key value is saved only single time each in the cluster and the cluster index, no concern how many rows of different tables hold the value.

Q. What's Cluster and Non-Cluster Indexes ?

A clustered Index sort the data in a table physically.
A non-clustered Index doesn't sort the data physically.

As clustered Index sort the data physically, So there can be only one Clustered index per table.
where as there can be many non-clustered index in table.
(with a maximum of 255 such indexes per table a very authentic possibility. i.e. every single column can be utilize for non-cluster indexing )

Q. when you can use a clustered or a non clustered index????
A. The clustered is a safe bet if you are working with a table having a large number of unique data, such as a table containing the employee IDs for the different members of an organization. These IDs are always unique, and using a clustered index is a good way of retrieving this large volume of unique data rapidly. On the other hand, a non clustered index is the best approach if you have a table that does not contain too many such unique values. These are just some of the differences between the two. You can read in detail about these differences by putting a search on the Internet for the differences between the two.

- - - - - -- - - - -- - - -

Monday, April 25, 2011

BST to Doubly Link List

To solve this problem, First we will analyze the different Cases :-
  Case 1: Leaf Node - left & right child is Null
  Case 2: No Left Subtree   - left Child is Null
  Case 2: No Right Subtree  - right Child is Null
  Case 2: No Left Subtree   - left Child is Null

Tuesday, April 5, 2011

Java 'ArrayList' Pseudocode ....


protected int modCount = 0;




ArrayList(int initialSize)
        IF  initialSize<0  THEN
                       Throw exception "Invalid Size"
       else
             arrayElement= new Object[initialSize];
        
ArrayList() 
  Call ArrayList(defaultSize); // default-size is 10

ArrayList(Collection<? extends E> C)
     arrayElement = C.toArray();
     size = arrayElement.length;
     IF arrayElement.getClass() != Object[].class THEN
                 arrayElement = Arrays.copyOf(arrayElement, size, Object[].class);

ensureCapacity(int newCapacity) 
   modCount++
   oldCapacity  = arrayElement.length;
    IF newCapacity > oldCapacity THEN
         Object[] oldData = arrayElement;
         newCap = (oldCap *3)/2 +1;
         IF newCap < newCapacity THEN
                   newCap=newCapacity;

         ENDIF
    END IF
  arrayElement =Arrays.copyOf(arrayElement, newCap); // My own implementation is at the end.

add(E data)
    ensureCapacity(size + 1);  // Increments modCount!!
    elementData[size++] = data;



add(int index, E element)
 IF index > size OR  index < 0 THEN
        throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);
 ENDIF
 ensureCapacity(size+1);  // Increments modCount!!
 System.arraycopy(elementData, index, elementData, index + 1, size - index); //shifting the right hand side elements by 1.
 elementData[index] = element;
 size++;

RangeCheck(int index)
   IF index >= size THEN
        throw new IndexOutOfBoundsException( "Index: "+index+", Size: "+size);

 remove(int index)
  RangeCheck(index)
  modCount++;   // modification count
  Object oldVal = elementData.get(index);
  int numMoved = size - index - 1;


addAll(Collection<? extends E> c)





Object[] a = c.toArray();
length = a.length;
ensureCapacity(size + numNew);
System.arraycopy(a, 0, elementData, size, numNew);
 size = size + numNew;
return numNew != 0;




  ........... to be continued (will add other details later)

Wednesday, March 23, 2011

Advantages of Iterator over forEach

1. Iterator is a design pattern and is a light-weight container.
2. Iterator doesnt need to know what the collection is (i.e. a List or sth else )
3. Using iterator ,we can remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering.
4. Similarly, forEach is not usable for loops where you need to replace elements in a list or array as you traverse it, but Iterator can be used.
5 .Finally, forEach is not usable for loops that must iterate over multiple collections in parallel.

Friday, March 4, 2011

finally Vs finilize


  • finally – The finally block always executes when the try block exits, except System.exit(0) call. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

  • finalize() – method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.

Wednesday, February 23, 2011

Equilibrium index of an Array

Ques :What is "Equilibrium index of an Array" ?
Ans:   Equilibrium index of an Array is an index of Array, such that the sum of elements at lower indices is equal to the sum of elements at higher indices. Value of element at the index is not taken into account.
For example, In the below Array:
Array-7   1    5    -4    3   0
Index        0   1    2   3   4    5   6
So here Index 3 and 6 are equilibrium index.
3 is an equilibrium index, because:     A[0]+A[1]+A[2]  = A[4]+A[5]+A[6]
6 is also an equilibrium index, because: A[0]+A[1]+A[2]+A[3]+A[4]+A[5] = 0

Method-1: Brute-Force method
 This method uses two loops to find the leftSum and rightSum for each index while traversing the array. 
void printEquilibriumIndexes(int arr[], int n){
    for (int i = 0; i < n; ++i){
        int leftSum = 0, rightSum = 0;
        for (int j=0; j<i; j++)
            leftSum += arr[j];
        for(int j=i+1; j<n; j++)
            rightSum += arr[j];       
        if (leftSum == rightSum)
           System.out.println("Index : "+i);
    }
}

Time complexity: O(n^2) 
Method-2: In this more efficient method where we keep track of the sum of all the elements in the Array and hence do not calculate the leftSum and rightSum from scratch but just update them based on the current index.
/**
 * This function will print all the Equilibrium Indexes in array arr
 */
void printEquilibriumIndexes(int arr[], int n){
    int rightSum = 0;   // Sum of all the Elements to the right of an Element
    int leftSum = 0; // Sum of all the Elements to the left of an Element

    for (int i=0; i<n; ++i)
        rightSum += arr[i];

    for (int i = 0; i < n; ++i){
        rightSum -= arr[i];
        if (leftSum == rightSum)
           System.out.println("Index: "+i);

        leftSum += arr[i];
    }
}