Tuesday, April 19, 2016

TreeSet over HashSet

When to go for TreeSet over HashSet
1. Sorted unique elements are required instead of unique elements.The sorted list given by TreeSet is
   always in ascending order.

2. TreeSet has greater locality than HashSet. If two entries  are near by in the  order, then TreeSet 
   places them near each  other in  data structure and  hence in memory,  while HashSet  spreads  the 
   entries all over memory  regardless of the keys they are associated to. 
   As we know  Data reads  from the hard drive  takes  much more latency time than data read from the 
   cache or memory.In case data needs to be read from hard drive than prefer TreeSet as it has greater
   locality than HashSet.

3. TreeSet uses Red- Black tree algorithm underneath to sort out the elements. When one need to perform
   read/write operations frequently, then TreeSet is a better option.

Saturday, April 16, 2016

Java Singleton

Java singleton class is per classloader.
Java Singleton Rules for implementing the singleton classes, but the class should be instantiated only once 
per classloader. Here is the basic steps for implementing the Java Singleton class.

a) When you say singleton class, there should be only one instance of that class can be created.
b) Constructor of that class has to be made as private to avoid instantiation from external classes.
c) Declare a static variable to store the instance for that class.
d) Declare a method that returns the instance of that class.
With the above basic rules, one can classify Java Singleton implementation into the following categories:

1) Eager Initialization
2) Static Block Initialization
3) Lazy Initialization
4) Thread Safe Singleton

Eager Initialization

In eager initialization, the singleton instance is created at the time of loading class loading. This is 
the easiest way to create the singleton instance for your singleton class. But, the main drawback of this
approach is that the instance will be created even though it is not used by any of the client application.
In this approach, you have to just create instance in the static variable declaration.  This approach 
doesn’t provide any option for exception handling.

Here is the example for eager initialization of singleton instance:

public class EagerInitialization {
    private static final EagerInitialization instance = new EagerInitialization();
    private EagerInitialization(){}
    public static EagerInitialization getInstance(){
        return instance;
    }
}

Static Block Initialization

This also falls under the eager initialization, the only difference is that instance creation is completed 
inside the static initializer block.  This approach doesn’t provide any option for exception handling.

Here is the example for static block initialization of singleton instance:

public class StaticBlockInitialization { 
    private static StaticBlockInitialization singletonInstance;     
    private StaticBlockInitialization(){}     
    static{
        try{
            singletonInstance = new StaticBlockInitialization();
        }catch(Exception e){
            throw new RuntimeException("Exception occured while creating the singleton instance");
        }
    }     
    public static StaticBlockInitialization getInstance(){
        return singletonInstance;
    }
}

Lazy Initialization

In this approach, we are creating the instance only after loading the class and first invocation of the
instance. This will avoid pre-initializing the instance where you don’t need the instance it is requested
by the service.

This approach works fine when this class is executed in the single threaded environment, but this will not
work fine in the multi-threaded environment when multiple threads are trying to get the new instance 
simultaneously 

Here is the simple example for Java Singleton class using lazy initialization approach:

class Singleton {
 private Singleton() {}
 private static Singleton singleton;
 private int value = 1;
 public static Singleton getInstance() {
  if (singleton == null) {
   singleton = new Singleton();
  }
  return singleton;
 }
 public int getValue() {
  return value;
 }
 public void setValue(int value) {
  this.value = value;
 } 
}

public class Main {
 public static void main(String args[]) {
  Singleton singleton = Singleton.getInstance();
  System.out.println("Value 1 : " + singleton.getValue());
  singleton.setValue(2);
  Singleton singleton2 = Singleton.getInstance();
  System.out.println("Value 2: " + singleton2.getValue());
 }
}

Thread Safe Singleton

This is similar to the above approach except that the method used for creating the singleton instance 
is synchronized.This approach is the most safest and best solution to implement the singleton instance, 
but it has the performance issues when multiple threads to trying to access the instance simultaneously.
Here is the example for thread safe singleton instance:

public class ThreadSafeInstance { 
    private static ThreadSafeInstance singletonInstance;
    private ThreadSafeInstance(){}
    public static synchronized ThreadSafeInstance getInstance(){
        if(singletonInstance == null){
            singletonInstance = new ThreadSafeInstance();
        }
        return singletonInstance;
    }
}

Wednesday, March 30, 2016

Best Example for Object Sorting, Comparable, Comparator & Inner class

Object sorting in Java using Comparable & Comparator Interface and Inner class
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 *
 * Java program to test Object sorting in Java. This Java program
 * test Comparable and Comparator implementation provided by Order
 * class by sorting list of Order object in ascending and descending order.
 * Both in natural order using Comparable and custom Order using Comparator in Java
 *
 */
public class ObjectSortingExample {

    public static void main(String args[]) {
      
        //Creating Order object to demonstrate Sorting of Object in Java
        Order ord1 = new Order(101,6000, "Sony");
        Order ord2 = new Order(102,2000, "Hitachi");
        Order ord3 = new Order(103,4000, "Philips");
      
        //putting Objects into Collection to sort
        List orders = new ArrayList();
        orders.add(ord3);
        orders.add(ord1);
        orders.add(ord2);
      
        //printing unsorted collection
        System.out.println("Unsorted Collection : " + orders);
      
        //Sorting Order Object on natural order - ascending
        Collections.sort(orders);
      
        //printing sorted collection
        System.out.println("List of Order object sorted in natural order : " + orders);
      
        // Sorting object in descending order in Java
        Collections.sort(orders, Collections.reverseOrder());
        System.out.println("List of object sorted in descending order : " + orders);
              
        //Sorting object using Comparator in Java
        Collections.sort(orders, new Order.OrderByAmount());
        System.out.println("List of Order object sorted using Comparator - amount : " + orders);
      
        // Comparator sorting Example - Sorting based on customer
        Collections.sort(orders, new Order.OrderByCustomer());
        System.out.println("Collection of Orders sorted using Comparator - by customer : " + orders);
    }
}

/*
 * Order class is a domain object which implements
 * Comparable interface to provide sorting on natural order.
 * Order also provides couple of custom Comparators to
 * sort object based upon amount and customer
 */
class Order implements Comparable {

    private int orderId;
    private int amount;
    private String customer;

    /*
     * Comparator implementation to Sort Order object based on Amount
     */
    public static class OrderByAmount implements Comparator {

        @Override
        public int compare(Order o1, Order o2) {
            return o1.amount > o2.amount ? 1 : (o1.amount < o2.amount ? -1 : 0);
        }
    }

    /*
     * Another implementation or Comparator interface to sort list of Order object
     * based upon customer name.
     */
    public static class OrderByCustomer implements Comparator {

        @Override
        public int compare(Order o1, Order o2) {
            return o1.customer.compareTo(o2.customer);
        }
    }

    public Order(int orderId, int amount, String customer) {
        this.orderId = orderId;
        this.amount = amount;
        this.customer = customer;
    }

  
    public int getAmount() {return amount; }
    public void setAmount(int amount) {this.amount = amount;}

    public String getCustomer() {return customer;}
    public void setCustomer(String customer) {this.customer = customer;}

    public int getOrderId() {return orderId;}
    public void setOrderId(int orderId) {this.orderId = orderId;}

    /*
     * Sorting on orderId is natural sorting for Order.
     */
    @Override
    public int compareTo(Order o) {
        return this.orderId > o.orderId ? 1 : (this.orderId < o.orderId ? -1 : 0);
    }
  
    /*
     * implementing toString method to print orderId of Order
     */
    @Override
    public String toString(){
        return String.valueOf(orderId);
    }
}

Saturday, April 18, 2015

Display the Area of a circle while drawing that circle in openlayers


<html>
<head>
<title>OpenLayers Dynamic Measure Crcle Radius</title>
<script src="OpenLayers.js"></script>
<script src="DynamicMeasure.js"></script>
<script type="text/javascript">
var map, layerOsm,vectors, polygonControl,polygonLayerBuffer;  
var lonLatFrankfurt = new OpenLayers.LonLat(966375, 6466128);  
 
function init() {           
 map = new OpenLayers.Map('map');  
 layerOsm = new OpenLayers.Layer.OSM("Simple OSM Map");  
 //map.addLayer(layerOsm);  
     
 polygonLayerBuffer = new OpenLayers.Layer.Vector("Polygon Layer Buffer");
 polyOptions = {sides: 40};  
 /*polygonControl = new OpenLayers.Control.DrawFeature(polygonLayerBuffer,
 OpenLayers.Handler.RegularPolygon,
 {handlerOptions: polyOptions});*/
     
 var polygonArea;       
 polygonControl = new OpenLayers.Control.DynamicMeasure(
 OpenLayers.Handler.RegularPolygon, {
 persist: true,
 handlerOptions: {
  sides: 100
 },
 callbacks: { move: function(evt) {
  console.log(evt);
  var element = document.getElementById('area');
  polygonArea = evt.getArea()/1000000;
  if(polygonArea < 1) 
    element.innerHTML =" Dyanmic Area "+ (polygonArea*1000000).toFixed(3)+ 
                                    " m<sup>2</" + "sup>";
  else
   element.innerHTML =" Dyanmic Area "+ polygonArea.toFixed(3)+ 
                                    " km<sup>2</" + "sup>";
  } 
  }
 });
         
 polygonControl.events.on({
 "measure": handleMeasurements,
 "measurepartial": handleMeasurements
 });
 
 map.addControl(polygonControl);
 map.addLayers([layerOsm,polygonLayerBuffer]);
 map.setCenter(  
 lonLatFrankfurt,  
 10  
 ); 

 polygonControl.activate();
  
}
 
 function featureModified(event) {
 var bounds = event.feature.geometry.getBounds();
 var answer = "bottom: " + bounds.bottom + "\n";
 answer += "left: " + bounds.left + "\n";
 answer += "right: " + bounds.right + "\n";
 answer += "top: " + bounds.top + "\n";
 alert(answer);
 }
 
 function handleMeasurements(evt){
 //console.log(evt);
 var geometry = evt.geometry;
 var units = evt.units;
 var order = evt.order;
 var measure = evt.measure;
 var element = document.getElementById('output');
 var position = (map.getLonLatPxFromViewPortPx);
 var out = "";
 if(order == 1){
  out += "Distance: " + measure.toFixed(3) + " " + units;
 }else{
  out += "Area: " + measure.toFixed(3) + " " + units + "<sup>2</" + "sup>";
 }
 element.innerHTML = out;
 }
  
 
</script>
</head>

<body onload="init()"> 
 Click & Drag on Map To Draw Circle
 <div id="output"></div>
 <div id="area"></div>
 <div id="map" style="height:500px;"></div> 
</body>
</html>

Friday, June 6, 2014

JQuery Popup Example

Simple Popup
<!DOCTYPE html>
<html>
    <head>
        <style>
            #modal {
                position:absolute;
                background:gray;
                padding:8px;
            }

            #content {
                background:white;
                padding:20px;
            }

            #close {
                position:absolute;
                background:url(close.png);
                width:24px;
                height:27px;
                top:-7px;
                right:-7px;
            }
        </style>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script>
            var modal = (function(){
                // Generate the HTML and add it to the document
                $modal = $('<div id="modal"></div>');
                $content = $('<div id="content"></div>');
                $close = $('<a id="close" href="#"></a>');

                $modal.hide();
                $modal.append($content, $close);

                $(document).ready(function(){
                    $('body').append($modal);                       
                });

                $close.click(function(e){
                    e.preventDefault();
                    $modal.hide();
                    $content.empty();
                });
                // Open the modal
                return function (content) {
                    $content.html(content);
                    // Center the modal in the viewport
                    $modal.css({
                        top: ($(window).height() - $modal.outerHeight()) / 2, 
                        left: ($(window).width() - $modal.outerWidth()) / 2
                    });
                    $modal.show();
                };
            }());

            // Wait until the DOM has loaded before querying the document
            $(document).ready(function(){
                $('a#popup').click(function(e){
                    modal("<p>This is popup's content.</p>");
                    e.preventDefault();
                });
            });
        </script>
    </head>
    <body>
        <a id='popup' href='#'>Simple popup</a>
    </body>
</html>
Note: close.png (Dimensions: 24 X 27)