Sunday, 19 January 2014

Comparable vs Comparator

A java program using Comparable Interface  :

package org.pallav.sort;                                                                                                  
                                                                                                                          
public class Employee implements Comparable {                                                                             
                                                                                                                          
    /**                                                                                                                   
     * @author pallav rajput                                                                                              
     */                                                                                                                   
                                                                                                                          
    int empid;                                                                                                            
    String name;                                                                                                          
    int salary;                                                                                                           
                                                                                                                          
    public Employee(int empid, String name, int salary) {                                                                 
        this.empid = empid;                                                                                               
        this.name = name;                                                                                                 
        this.salary = salary;                                                                                             
                                                                                                                          
    }                                                                                                                     
                                                                                                                          
    @Override                                                                                                             
    public int compareTo(Object arg0) {
        Employee employee = (Employee) arg0; 
        return (this.empid < employee.empid) ? -1
        : (this.empid > employee.empid) ? 1 : 0;
                                                                                                                          
    }                                                                                                                     
                                                                                                                          
    public int getEmpid() {                                                                                               
        return empid;                                                                                                     
    }                                                                                                                     
                                                                                                                          
    public void setEmpid(int empid) {                                                                                     
        this.empid = empid;                                                                                               
    }                                                                                                                     
                                                                                                                          
    public String getName() {                                                                                             
        return name;                                                                                                      
    }                                                                                                                     
                                                                                                                          
    public void setName(String name) {                                                                                    
        this.name = name;                                                                                                 
    }                                                                                                                     
                                                                                                                          
    public int getSalary() {                                                                                              
        return salary;                                                                                                    
    }                                                                                                                     
                                                                                                                          
    public void setSalary(int salary) {                                                                                   
        this.salary = salary;                                                                                             
    }                                                                                                                     
                                                                                                                          
}                       



                                                                                                                                                                                                                                        
package org.pallav.sort;

import java.util.ArrayList;
import java.util.Collections;

public class ComparableMain {

    /**
     * @author Pallav Rajput
     */

    public static void main(String[] args) {

        Employee emp = new Employee(1, "Pallav", 44000);
        Employee emp1 = new Employee(7, "Pranay", 45000);
        Employee emp2 = new Employee(11, "Abhinay", 42000);
        Employee emp3 = new Employee(8, "Salty", 42000);
        Employee emp4 = new Employee(4, "Shikhar", 38000);

        ArrayList<Employee> listofEmployee = new ArrayList<Employee>();

        listofEmployee.add(emp);
        listofEmployee.add(emp1);
        listofEmployee.add(emp2);
        listofEmployee.add(emp3);
        listofEmployee.add(emp4);

        System.out.println("Before Sort  : ");

        for (int i = 0; i < listofEmployee.size(); i++) {
            Employee employee = (Employee) listofEmployee.get(i);
            System.out.println("Employee Id: " + employee.getEmpid() + "||"
                    + "Employee Name: " + employee.getName() + "||"
                    + "Employee Salary:" + employee.getSalary());
        }

        Collections.sort(listofEmployee);

        for (int i = 0; i < listofEmployee.size(); i++) {
            Employee employee = (Employee) listofEmployee.get(i);
            System.out.println("Employee Id: " + employee.getEmpid() + "||"
                    + "Employee Name: " + employee.getName() + "||"
                    + "Employee Salary:" + employee.getSalary());
        }

    }

}

Output :

Before Sort  :
Employee Id: 1 || Employee Name: Pallav || Employee Salary:44000
Employee Id: 7 || Employee Name: Pranay || Employee Salary:45000
Employee Id: 11 || Employee Name: Abhinay || Employee Salary:42000
Employee Id: 8 || Employee Name: Salty || Employee Salary:42000
Employee Id: 4 || Employee Name: Shikhar || Employee Salary:38000

After Sort  :
Employee Id: 1 || Employee Name: Pallav || Employee Salary:44000
Employee Id: 4 || Employee Name: Shikhar || Employee Salary:38000
Employee Id: 7 || Employee Name: Pranay || Employee Salary:45000
Employee Id: 8 || Employee Name: Salty || Employee Salary:42000
Employee Id: 11 || Employee Name: Abhinay || Employee Salary:42000


A java program using Comparator Interface  : 


package org.pallav.sort;                                                                                                  
                                                                                                                          
public class Employee  {                                                                             
                                                                                                                          
    /**                                                                                                                   
     * @author pallav rajput                                                                                              
     */                                                                                                                   
                                                                                                                          
    int empid;                                                                                                            
    String name;                                                                                                          
    int salary;                                                                                                           
                                                                                                                          
    public Employee(int empid, String name, int salary) {                                                                 
        this.empid = empid;                                                                                               
        this.name = name;                                                                                                 
        this.salary = salary;                                                                                             
                                                                                                                          
    }                                                                                                                     
                                                                                                                          
    public int getEmpid() {                                                                                               
        return empid;                                                                                                     
    }                                                                                                                     
                                                                                                                          
    public void setEmpid(int empid) {                                                                                     
        this.empid = empid;                                                                                               
    }                                                                                                                     
                                                                                                                          
    public String getName() {                                                                                             
        return name;                                                                                                      
    }                                                                                                                     
                                                                                                                          
    public void setName(String name) {                                                                                    
        this.name = name;                                                                                                 
    }                                                                                                                     
                                                                                                                          
    public int getSalary() {                                                                                              
        return salary;                                                                                                    
    }                                                                                                                     
                                                                                                                          
    public void setSalary(int salary) {                                                                                   
        this.salary = salary;                                                                                             
    }                                                                                                                     
                                                                                                                          
}                          

package org.pallav.sort;

import java.util.Comparator;

public class SortbyIdComparator implements Comparator<Employee> {

    public int compare(Employee emp1, Employee emp2) {
        // TODO Auto-generated method stub
        return (emp1.getEmpid() < emp2.getEmpid()) ? -1
                : (emp1.getEmpid() > emp2.getEmpid()) ? 1 : 0;
    }

}


package org.pallav.sort;   

import java.util.ArrayList;
import java.util.Collections;

public class ComparatorMain {

   
    /**
     * @author pallav rajput
     */

    public static void main(String[] args) {

        Employee emp = new Employee(1, "Pallav", 44000);
        Employee emp1 = new Employee(7, "Pranay", 45000);
        Employee emp2 = new Employee(11, "Abhinay", 42000);
        Employee emp3 = new Employee(8, "Salty", 42000);
        Employee emp4 = new Employee(4, "Shikhar", 38000);

        ArrayList<Employee> listofEmployee = new ArrayList<Employee>();

        listofEmployee.add(emp);
        listofEmployee.add(emp1);
        listofEmployee.add(emp2);
        listofEmployee.add(emp3);
        listofEmployee.add(emp4);

        System.out.println("Before Sort  : ");

        for (int i = 0; i < listofEmployee.size(); i++) {
            Employee employee = (Employee) listofEmployee.get(i);
            System.out.println("Employee Id: " + employee.getEmpid() + " || "
                    + "Employee Name: " + employee.getName() + " || "
                    + "Employee Salary:" + employee.getSalary());
        }

        Collections.sort(listofEmployee, new SortbyIdComparator());
       
        System.out.println("After Sort  : ");

        for (int i = 0; i < listofEmployee.size(); i++) {
            Employee employee = (Employee) listofEmployee.get(i);
            System.out.println("Employee Id: " + employee.getEmpid() + " || "
                    + "Employee Name: " + employee.getName() + " || "
                    + "Employee Salary:" + employee.getSalary());
        }

    }

}

Output :

Before Sort  :
Employee Id: 1 || Employee Name: Pallav || Employee Salary:44000
Employee Id: 7 || Employee Name: Pranay || Employee Salary:45000
Employee Id: 11 || Employee Name: Abhinay || Employee Salary:42000
Employee Id: 8 || Employee Name: Salty || Employee Salary:42000
Employee Id: 4 || Employee Name: Shikhar || Employee Salary:38000

After Sort  :
Employee Id: 1 || Employee Name: Pallav || Employee Salary:44000
Employee Id: 4 || Employee Name: Shikhar || Employee Salary:38000
Employee Id: 7 || Employee Name: Pranay || Employee Salary:45000
Employee Id: 8 || Employee Name: Salty || Employee Salary:42000
Employee Id: 11 || Employee Name: Abhinay || Employee Salary:42000

Wednesday, 15 January 2014

What happens when i make any static method as synchronized ??


In Java multi-threading, Synchronization is achieved by the use of locks, each of which is associated with an object by the JVM. For a thread to work on an object, it must have control over the lock associated with it, it must “hold” the lock. Only one thread can hold a lock at a time. If a thread tries to take a lock that is already held by another thread, then it must wait until the lock is released.

Basically there are two types of locks

Object level locklock on instance of the class, when any synchronized method or block are non-static.

Class level lock : lock on the Class, in case of synchronized method or block are static.

A synchronized method or block works on a given monitor. Synchronized non-static methods all synchronize on the Java instance of a class. Each instance has a lock monitor. In case of static methods, what object does static synchronized methods use for locking? The static synchronized statements obtain a lock on the Class object. The following example show you few ways to access the class object:

class MyClass {

 ....

   public static void main(String[] args) {
      //you can access class object through an instance of that class
      MyClass objectinstance = new MyClass();
      java.lang.Class myclass1 = objectinstance.getClass();

      //non-instance ways
      java.lang.Class myclass2 = Myclass.class;
 java.lang.Class myclass3 = Class.forName("MyClass");
    }

}
The JVM creates a Class object when the class is loaded (When it is used for the first time). Once a class is loaded into a JVM, the same class will not be loaded again. The JVM creates one instance of Class for each class that is loaded, The Class instances are Objects and can be synchronized via static synchronized methods.
For example
class MyClass  {
  ...
  public synchronized static someMethod() {
    ...
  }
  ...
}
It is the equivalent to the following static synchronized block:
synchronized ( MyClass.class ) {
...
}

The Lock on object or instance of class is totally independent from Class level lock. both will execute independently. There will be never any interference between object lock and class level lock.



Wednesday, 8 January 2014

Iterable interface and Iterator interface

Iterable interface is in  java.lang  package and  Iterator interface in  java.util package

public interface Iterable

Implementing this interface allows an object to be the target of the "foreach" statement.
This interface has one method :

iterator(), Returns an iterator over a set of elements.








The implementing classes for this interface is AbstractCollection, AbstractList, AbstractQueue, AbstractSequentialList, AbstractSet e.t.c

also iterator() is implemented in classes ArrayList , HashSet and few more classes.

Basically ArrayList override iterator() from AbstractList, 
and in same way HashSet override iterator() from AbstractSet

 public interface Iterator

An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways:
  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  • Method names have been improved.
This interface is a member of the Java Collections Framework.

This interface has three methods :

hasNext(),
next(),
remove()









Iterator example using ArrayList, Set and Map

package com.java.pallav;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class ListCompare {
    private static ArrayList<Object> a1, a2, a3;

    public static void main(String[] args) {

        a1 = new ArrayList<Object>();

        a1.add(12);

        a1.add(14);
        a1.add(16);
        a1.add(18);
        a1.add(20);

        a2 = new ArrayList<Object>();


        a2.add(12);

        a2.add(18);
        a2.add(20);
        a2.add(21);

        // Iterate a1 elements

        Iterator<Object> iterator = a1.iterator();

        while (iterator.hasNext()) {

            Object object = (Object) iterator.next();
            System.out.println("*********START********");
            System.out.println(object);
            System.out.println("**********END*********");

        }


        // creating a3, new instance of ArrayList

        // compare a1 and a2 list, if the elements of a2 is not available in a1
        // then keep that elements in a3
       
        a3 = new ArrayList<Object>();
        for (int i = 0; i < a2.size(); i++) {

            if (a1.contains(a2.get(i))) {

                a3.add(a2.get(i));
            }
        }
        // print a3 elements
        for (Object a : a3) {

            System.out.println(a);

        }

        // How to convert an ArrayList a1 into type Set

        Set<Object> s = new HashSet<Object>(a1);

        Map<Object, Object> m = new HashMap<Object, Object>();

        m.put(10, "Hello");
        m.put(20, "Hello1");
        m.put(30, "Hello2");
        m.put(40, "Hello3");
        m.put(50, "Hello4");

        // we can,t Iterate Map elements directly, hence convert it into type

        // Set using entrySet() of Map
        Iterator<Object> iterator2;
        Set s2 = m.entrySet();

        iterator2 = s2.iterator();


        while (iterator2.hasNext()) {

            Object object = (Object) iterator2.next();
            System.out.println("*********START********");
            System.out.println(object);
            System.out.println("**********END*********");

        }


    }


}