Thursday, May 12, 2016

ArrayList and LinkedList

get(int index) method:
ArrayList internally uses arrays to store elements so.
Retrieving any elements from ArrayList is faster because elements are stored bases on indexing and thus ArrayList is ordered.
Think about children standing in a row for Morning Prayer. Think that there is only single row of few children.  Each child has specific position according to their ordering.
Suppose I want to know that which child is at position 5 or 6, I can get it easily because I know the position. Same as in case of Java array. You can get element in O(1) time from an array (elementArray[position] will give the element).
 So get(int index) method in ArrayList is fast. O(1). Thus random access is faster.

LinkedList: LinkedList in java uses doubly linked list to store the elements.
You can think doubly-linked list as a group of children holding hand of each other and making a row.  First child holding the hand of second child and second child holding the hand of first and third. Similarly last child hold the hand of second last and second last hold  the last and third last .
Now If I want to get any element on the basis of position get(int index) then I have to start from that node which is defined as first node (first child ). Now after traversing to that position I will get that element so it’s slower. I need to traverse for getting the element.
Here there is no indexing of children like children stating in Morning Prayer (ArrayList).
Suppose the position is in last then it will take O(n) time for getting the element. Where n is number of elements.
So get(int index) method in LinkedList is slower . O(n).


add(E element) and add(int position, E element):

Adding element in the last of ArrayList is always faster.
Suppose I want to add one more child in Morning Prayer row (it’s not queue which is FIFO based) or in row of children where children or holding each other by hand. The child will go and stands at last position of the row or in holding hand row.
If I say that this particular child will stand at position 8th then he will stand there and the entire child after position 7th will move right and make a space for this new child. Thus add(int position, E element) is costly than add(E element) in both.
The only difference is that there is a capacity limit that how many children can stand in a row – ArrayList. But there is no such constraint in case of holding hand row – LinkedList.
Due to this difference add(E element) or add(int position, E element) will be in O(n) time if capacity of ArrayList is already full because
1: ArrayList will increase its capacity
2: Copy all the elements into this new capacity array
3: Now it will add the element in the last or specified position.
There will be no such above thing in LinkedList.
If you are iterating the LinkedList then you are adding elements using ListIterator.add(E element) method then LinkedList is much faster.

remove(int position) and remove(E element):

Removing element from the last of ArrayList is always faster.
remove(E element) method will give same performance in both cases.
If you are iterating the LinkedList then you are removing elements using Iterator.remove() method then LinkedList is much faster.

Method availability:
LinkedList has methods addFirst(E element), addLast(E element).  getFirst(), getLast(), offer(E element), poll(), peek()  . ArrayList does not need such methods.
LinkedList needs extra memory for  maintaining pointer to next and previous nodes.

New Method added in JDK 8 List:
spliterator(): Creates a late-binding and fail-fast Spliterator over the elements in this list.

Conclusion: Go with ArrayList in all scenario except one that is if you have to do addition and deletion  using iterator’s remove and add (ListIterator) method while iterating the list then go with LinkedList.


References:  Oracle ArrayList

Wednesday, May 11, 2016

Inversion of control, Dependency Inversion, Dependency Injection

Inversion of control: It is a principle in which custom written portion of computer program receives the flow of control from a generic framework.
Custom written portion of computer program:    Whatever the code we write using Spring framework is an example of custom written portion of computer program.
Receives the flow of control from a generic framework: Our custom written computer program is governed by Spring framework.  Example:   object creation, scope, defining their dependencies and some other main activities are defined by spring framework.
It means that reusable code and problem specific code developed independently even though they operate together in application.
IOC is based on one principle ‘Do not call us, we will call you back’.  Example: Spring framework defines when our custom classes will be created and injected.  There are many such examples available with Spring framework.
Purpose of IOC: Increasing the modularity, reducing coupling and increasing the extensibility of the application program.

Service locator pattern, Dependency Injection, template method design pattern are the examples of Inversion of Control principle.
Dependency Inversion and Dependency Injection:
Dependency Inversion is a principal while dependency Injection is a design pattern that follows the dependency inversion principle.
Dependency Inversion principle states that:
            a: High level modules should not depend on low level modules. Both should depend on abstractions.
            b: Abstraction should not depend on details. Details should depend on abstraction.

Dependency injection is a software design pattern that implements inversion of control for resolving dependencies. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it. The service is made part of the client's state. Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern.

References: Wikipedia

Thursday, May 5, 2016

Objects which are equal but have different hash code



We can have two objects which are equal but have different hash code.
But you want to store it as key in Map interface then hashcode and equals both must be equal for the equal object.

import java.util.HashMap;
import java.util.Map;

/**
 * @author Arun
 */
public class EqualObjectsWithDifferentHashCode {

  private String name;
  private int age;

  public String getName() {
    return name;
  }

  public void setName(final String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(final int age) {
    this.age = age;
  }


  public static void main(String args[]) {

    final EqualObjectsWithDifferentHashCode one = new EqualObjectsWithDifferentHashCode();
    one.setAge(1);
    one.setName("A");
    final EqualObjectsWithDifferentHashCode two = new EqualObjectsWithDifferentHashCode();
    two.setAge(2);
    two.setName("B");
    final EqualObjectsWithDifferentHashCode three = new EqualObjectsWithDifferentHashCode();
    three.setAge(1);
    three.setName("A");

    final Map ss = new HashMap<>();
    ss.put(one, "ABC");
    ss.put(two, "XYZ");
    ss.put(three, "KLM");

    // print hashcode of objects. Both object will have different hashcode.
    System.out.println("hashcode of One=" + one.hashCode());
    System.out.println("hashcode of Three=" + three.hashCode());

    // check equality of the objects
    System.out.println("Both objects are equal=" + one.equals(three));

    // now try to fetch object from the Map
    System.out.println(ss.get(three));
  }

  @Override
  public int hashCode() {
    // It is just for example. Do not follow it. It will always return different hashcode.
    return (int) Math.abs((Math.random() * 1000));
  }


  @Override
  public boolean equals(final Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    EqualObjectsWithDifferentHashCode other = (EqualObjectsWithDifferentHashCode) obj;
    if (age != other.age)
      return false;
    if (name == null) {
      if (other.name != null)
        return false;
    } else if (!name.equals(other.name))
      return false;
    return true;
  }

}