Saturday, 19 May 2012

Core Java


Comparator & Comparable in java

Programmers are usually confused between “comparable” & “Comparator” interface. Comparable interface has “compareTo” method which is normally used for natural ordering but Comparator interface has “comparable” method which contain 2 parameter which is used for sort the object based on more than one parameter.
/** Use the Collections.sort to sort a List
 **
 ** When you need natural sort order you can implement
 ** the Comparable interface.
 **
 ** If You want an alternate sort order or sorting on different properties
 * then implement a Comparator for your class.
 */
package com.jsd.in.sorting;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Farmer implements Comparable{
      private String name;
      private int age;
      private long income;

      /***
       *
       * @param name
       * @param age
       */
      public Farmer(String name, int age)
      {
            this.name = name;
            this.age = age;
      }
      /***
       *
       * @param name
       * @param age
       * @param income
       */
      public Farmer(String name, int age,long income)
      {
            this.name = name;
            this.age = age;
            this.income=income;
      }
      public String getName()
      {
            return name;
      }

      public int getAge()
      {
            return age;
      }

      public String toString()
      {
            return name + " : " + age;
      }
      public long getIncome() {
            return income;
      }
    /***
     *
     * @param income
     */
      public void setIncome(long income) {
            this.income = income;
      }

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

      public void setName(String name) {
            this.name = name;
      }
      /***
       *  implements the natural order for this class
       * @param obj
       * @return int
       */
      public int compareTo(Object obj) {
            System.out.println("Comparable");
            return getName().compareTo(((Farmer)obj).getName()); //ASC - order
            //return ((Farmer)obj).getName().compareTo(getName()); // DEC - order
      }
      static class AgeComparator implements Comparator {
            @Override
            public int compare(Object o1, Object o2) {
                  // TODO Auto-generated method stub
                  Farmer farmer1 = (Farmer) o1;
                  Farmer farmer2 = (Farmer) o2;
                  if(farmer1.getIncome() == 0 && farmer2.getAge() == 0) {
                        System.out.println("getIncome() == 0 &&");
                        return farmer1.getAge() - farmer2.getAge();
                  } else {
                        System.out.println("(int)(farmer1.getIncome()");
                        //return (int)(farmer1.getIncome() - farmer2.getIncome()); // lower to high
                        return (int)(farmer2.getIncome() - farmer1.getIncome());
                  }
            }
           
      }
      public static void main(String args[]) {
            List<Farmer> farmer =  new ArrayList<Farmer>();
            farmer.add(new Farmer("D",28));
            farmer.add(new Farmer("B",23));
           
            Collections.sort(farmer);
            System.out.println("Sort in natural order");
            System.out.println("T: "+farmer);
           
            Collections.sort(farmer,Collections.reverseOrder());
            System.out.println("Sort by reverse natural order");
            System.out.println("T: "+farmer);
           
            Collections.sort(farmer, new AgeComparator());
            System.out.println("Sort using Age comparator");
            System.out.println("T"+farmer);
           
            /*List farmerIncome = new ArrayList();
            farmerIncome.add(new Farmer("E",22,30));*/
             farmer =  new ArrayList<Farmer>();
            farmer.add(new Farmer("E",29,30));
            farmer.add(new Farmer("G",27,45));
           
           
           
            Collections.sort(farmer, new AgeComparator());
            System.out.println("Sort using Age comparator Butincome wise");
            System.out.println("T: "+farmer);
           
            //============
            List<Farmer> farmerIncome = new ArrayList<Farmer>();
            farmerIncome.add( new Farmer("Joe", 34,33));
            farmerIncome.add( new Farmer("Ali", 13,3));
            farmerIncome.add( new Farmer("Mark", 25,666));
            farmerIncome.add( new Farmer("Dana", 66,7));
           
            Collections.sort(farmerIncome, new AgeComparator());
            System.out.println("Sort using Age comparator Butincome wise");
            System.out.println("T: "+farmerIncome);
      }
 }

Output

Sort in Natural order
[Ali : 13, Dana : 66, Joe : 34, Mark : 25]
 Sort by reverse natural order
 [Mark : 25, Joe : 34, Dana : 66, Ali : 13]
  Sort using Age Comparator
  [Ali : 13, Mark : 25, Joe : 34, Dana : 66]
   Sort using Age Comparator But Income Wise
   [Joe : 34, Ali : 13, Mark : 25, Dana : 66]


ð  The Collections and Arrays can sorted using the method in the API. Java.util.Collections.sort()  and Arrays.sort() method  is used to sort the Collections and Arrays. Remember that argument passed to collections.sort() method must implements the Comparable interface otherwise we will get a compilation error.
ð  The comparable interface:
o   This interface is used by Collections.sort() and Arrays.sort() method to sort the list and array of objects.
o   To implement this interface, a class must  implement a single method compareTo().
o   Let us see the invocation of compareTo() method:
§  int  x = this.object.compareTo(anotherObject);
Here compareTo() method returns an int with the following meaning
ð  negative (-1) à if this object < another object
ð  zero (0) à if this object == another object
ð  positive (1) à if this object > another object
Before generics the compareTo () method takes an object rather than a specific type. Here we have to cast object to specific type. For Example see below code
Class DVDInfo impelements Comparable {
                //some code here
                Public int compareTo(Object obj) {
                                DVDInfo d = (DVDInfo) obj;
                                Return this.title.compareTo(d.title);
}
}
public class CompareTo

{

    public static void main(String[] args)

    {

        String str1 = "Welcome to RoseIndia team";

        String str2 = "Welcome to RoseIndia ";



        // Compare the two strings.

        int result = str1.compareTo(str2);

        if (result < 0)

        {

      // displays str1 is less than str 2

            System.out.println(str1 + "is less than"  + str2);

        }
        else if (result == 0)
        {
      // displays str1 is  equal to str 2
            System.out.println(str1 +"is equal to" + str2);
        }
        else 
        {
      // displays str1 is greater than str 2
    System.out.println(str1 +"is greater than" + str2);
        }
    }
}

ð  The comparator interface:-
o   The comparator interface gives you the capability to sort collection in different ways.
o   This interface is used sort instance of any class even if classes you can’t modify.
o   To implement this interface, a class must implement a single method compare().
o   Comparator.compare() method returns an int whose meaning is same as Comparable.compareTo() method’s return value.
ð  Comparing comparable to comparator:-
Difference between comparable & comparator interface
Comparable
Comparator
 java.lang.Comparable
Java.util.Compartor
Used for natural ordering [Note:- we have to use TreeSet class instead of HashSet class. Because TreeSet has order, which is not in HashSet.]
Ordering based of multiple attribute
compareTo(Object)  [obj.compareTo(null) throws exception & obj.equals(null) return false]
Comparable(Object,Object)
CompareTo compare two object, one being on which is calling & another is passed as argument
Comparable compare two objects, which is passed as method argument with each other.
compareTo return type is int. It return -1,0,1
Zero means true (value is equal)
Negative means not equals
Positive means value is empty  (in case of string)
Comparable return type is int. It also return -1,0,1.
Zero means true (value is equal)
Negative means not equals
Positive means value is empty (in case of string)
this.firstName.compareTo(obj.firstName) //ASC-Order
obj.firstName.compareTo(this.firstName) //DESC-Order

We must modify the class whose instance we want to sort.
We build a class separate from the class whose instances we want to sort.
Only one sort sequence can be created
Many sort sequence can be created
Implemented frequently in the API by: String, Wrapper classes, Date, Calender…
Meant to be implemented to sort instance of third party classes.
If you want to sort int type value then we have to convert it into wrapper class (Integer), after that we can call compareTo(Object) method on it.


ð  import java.util.ArrayList;
ð  import java.util.Collections;
ð  import java.util.Comparator;
ð  import java.util.Iterator;
ð   
ð   
ð  public class Student implements Comparable<Student> {
ð              private String name;
ð              private int score;
ð             
ð              public Student(String name, int score) {
ð                          this.name = name;
ð                          this.score = score;
ð              }
ð   
ð              public int compareTo(Student obj){
ð                          Integer i=new Integer(score);
ð                    //      return i.compareTo(obj.score); //asc
ð                          return (new Integer(obj.score)).compareTo(this.score); //desc
ð   
ð              }
ð                         
ð   
ð              public static void main(String args[]) {
ð                   ArrayList<Student> list = new ArrayList<Student>();
ð                     
ð                   list.add(new Student("Ann", 87));
ð                   list.add(new Student("Bob", 83));
ð                   list.add(new Student("Cat", 99));
ð                   list.add(new Student("Dan", 25));
ð                   list.add(new Student("Eve", 76));
ð                  
ð                   Iterator<Student> iter = list.iterator();
ð                   while (iter.hasNext()) {
ð                      Student s = iter.next();
ð                      System.out.println(s.name +  " + s.score);
ð                   }
ð                   System.out.println("Sorted List");
ð                   Collections.sort(list);
ð                   Iterator<Student> iter1 = list.iterator();
ð                   while (iter1.hasNext()) {
ð                      Student s = iter1.next();
ð                      System.out.println(s.name +  " + s.score);
ð                   }
ð                  
ð                   StudentName st1= new StudentName();
ð                   Collections.sort(list,st1);
ð                   Iterator<Student> iter2 = list.iterator();
ð                   while (iter2.hasNext()) {
ð                      Student s = iter2.next();
ð                      System.out.println(s.name +  " + s.score);
ð                   }
ð                  
ð                 
ð                  }
ð              static class StudentName implements Comparator<Student>{
ð                          public int compare(Student o1, Student o2) {
ð                                      return o1.name.compareTo(o2.name);
ð                          }
ð              }
ð  }
Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.

HashMap & Hash Tree
HashMap class implements java.util.Map interface & uses hashing for storage. Indirectly Map uses Set functionality so, it does not permit duplicates.
The TreeMap class implements java.util.Map interface & uses tree for storage. It provides the ordered map.
Allow Null both k,v
Not allow
Faster
Slower









HashMap & Hashtable
HASH MAP
HASH TABLE
Not Synchronized
Synchronized
Allow Null both k,v
Not allow
Faster
Slower
Iterator in the hash map is fail-safe
While the enumeration for the hash table is not fail-safe.
  containsKey(Object)
  containsValue(Object)
  contains(Object) (only compare the value)
  containsKey(Object)
  containsValue(Object)
HashSet
Tree Set
Store elements in hash table
Store in red-black tree
No order
Order (ASC/DESC)
Operation (add,remove,contain)
Operation (add,remove,contain,size)
Allow null value
Allow one null value, If we add 2 null value then throws NullPointerException.
A red-black tree is a type of binary search tree, so each node in the tree has a parent (except the root node) and at most two children. The tree as a whole will be identified by its root node. For ease of implementation, we will have each node retain a pointer to both its children as well as its parent node (null for the root). Keeping parent nodes costs space and is not strictly necessary, but makes it easy to follow the tree in any direction without maintaining an auxiliary stack. Our red-black tree will implement an associative array, and we will allow key and values of any class type
Vector
Array List
Initial capacity is 10
No initial capacity
Synchronized
Not Synchronized
Vector allows to store only objects not primitives.

Use iterator or enumeration
User Iterator ListIterator

Linked List
Array List
No initial capacity
No initial capacity
Not Synchronized
Not Synchronized
Faster
Slower
Easy to add, remove, delete element in linked list from any location.
It’s not easy as linked list.

Example of hashcode() & equals():-
Caution that needs to be taken is that while implementing the hashcode() method the fields that are present in the hashcode()
should not be the one which could change the state of object.
Consider the example:
public class FourWheeler implements Vehicle {

private String name;
private int purchaseValue;
private int noOfTyres;
public FourWheeler(){}

public FourWheeler(String name, int purchaseValue) {
this.name = name;
this.purchaseValue = purchaseValue;
}
public void setPurchaseValue(int purchaseValue) {
this.purchaseValue = purchaseValue;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + purchaseValue;
return result;
}
}
//Try running this snippet
FourWheeler fourWObj = new FourWheeler("Santro","300000);
map.put(fourWObj,"Hyundai);
fourWObj.setPurchaseValue("350000)
System.out.println(map.get(fourWObj));
//Output: null
We can see that inspite of passing the same object the value returned is null. This is because the hashcode() returned on
evaluation will be different since the purchaseValue is set to 350000 from 300000.
Though the above implementation is correct but it fails because for generating hashcode a changeable property (in this case
price) is selected. To make above implementation correct we can either exclued the property or include some other
property like noOfTyres and keep the logic of implementation same. Hence
we can conclude that the hashcode() should contain fields that doesn't change the state of object.
One compatible, but not all that useful, way to define hashCode() is like this:
public int hashcode(){
return 0;
}
This approach will yield bad performance for the HashMap. The conclusion which can be made is that the hashcode() should(not
must) return the same value if the objects are equal. If the objects are not equal then it must return different value.
=========================EXAMPLE -- OF -- REFLECTION===================

package com.core;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

class TestBean {
private String name;

public String getName() {

return name;
}

public void setName(String name) {
System.out.println(name);
this.name = name;
}

}

public class ReflectionTest {

/**
* @param args
* @throws IllegalAccessException
* @throws InstantiationException
* @throws InvocationTargetException
* @throws IllegalArgumentException
*/
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
// TODO Auto-generated method stub
Class zlass = Class.forName("com.core.TestBean");
TestBean testBean = (TestBean) zlass.newInstance();
Field filed[] = zlass.getFields();
Method[] method = zlass.getMethods();
for (Method methd : method) {
methd.setAccessible(true);
if (methd.getName().equals("setName")) {
methd.invoke(testBean, "Jagdeep");

}

}
}

}
=====================================================================

FIND MISSING NUMBER :

You can do this in O(n). Iterate through the array and compute the sum of all numbers. Now, sum of natural numbers from 1 to N, can be expressed as Nx(N+1)/2. In your case N=100.
Subtract the sum of the array from Nx(N+1)/2, where N=100.
That is the missing number. The empty slot can be detected during the iteration in which the sum is computed.

EXAMPLE:- 
import java.math.*;

class TestArray {

    public static void main(String args[]) {      
        int sum = 0;
        int idx = -1;
        int arr[] = new int[5];
        arr[0]=1;arr[1]=2;arr[4]=5;arr[3]=3;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == 0) {
                 idx = i;
            } else {
                 sum += arr[i];
            }
        }
        // the total sum of numbers between 1 and arr.length.
        int total = (arr.length + 1) * arr.length / 2;
        System.out.println("missing number is: " + (total - sum) + " at index " + idx);

          // create 2 BigDecimal objects
        BigDecimal bg1, bg2;

        bg1 = new BigDecimal("10.000");
        bg2 = new BigDecimal("10.000");

        //create int object
        int res;

        res = bg1.compareTo(bg2); // compare bg1 with bg2

        String str1 = "Both values are equal ";
        String str2 = "First Value is greater ";
        String str3 = "Second value is greater";

        if( res == 0 )
        System.out.println( str1 +"::"+bg1.intValue());
        else if( res == 1 )
        System.out.println( str2 +"::"+bg1.intValue());
        else if( res == -1 )
        System.out.println( str3 );
    }

}

DATE CALCULATION:-
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/***
 *
 * @author Jagdeep
 *
 */

public class DateCalculation {

    private static final String DEFAULT_FORMAT = "dd-MM-yy";
    private static final String DEFAULT_DATETIME_FORMAT = "dd-MM-yy hh:mm:ss";
    private static final String DEFAULT_DATETIME_MONTH_IN_CHAR_FORMAT = "dd-MMM-yy hh:mm:ss aa XXX";

    /***
     *
     * @param date
     * @param dateFormat
     * @return
     */
    public static String convertDateToString(Date date, String dateFormat) {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        return sdf.format(date);
    }
    /***
     *
     * @param date
     * @param dateFormat
     * @return
     */
    public static String convertDateToTimeString(Date date, String dateFormat) {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat,Locale.ENGLISH);
        return sdf.format(date);
    }
    /***
     *
     * @param date
     * @param dateFormat
     * @return
     * @throws ParseException
     */
    public static Date convertStringToDate(String date,String dateFormat) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        return sdf.parse(date);
    }
    /***
     *
     * @param now
     * @param days
     * @return
     */
    public static Timestamp updateTimestamp(Timestamp now,int days) {      
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);cal.set(Calendar.DATE,(cal.get(Calendar.DATE)+days));
        return new Timestamp(cal.getTime().getTime());
    }
    /***
     * This is used to get days difference between two timestamp.
     * @param first
     * @param second
     * @return java.sql.Timestamp
     */
    public static long getDaysDifference(Timestamp first, Timestamp second) {
        Calendar firstDate = Calendar.getInstance();
        Calendar secondDate = Calendar.getInstance();
           firstDate.setTime(first);secondDate.setTime(second);
           long diffInMillisec = firstDate.getTimeInMillis() - secondDate.getTimeInMillis();
        return Math.abs(diffInMillisec / (24 * 60 * 60 * 1000));         
    }
    /***
     * This check year is leap or not.
     * @param year
     * @return boolean
     */
    public static boolean isLeapYear(int year) {
        if ((year % 100 != 0) || (year % 400 == 0)) {
            return true;
        }
        return false;
    }
  
    /***
     * Timestamp format must be yyyy-mm-dd hh:mm:ss
     * @param timeStamp
     * @return java.sql.Timestamp
     */
    public static Timestamp convertStringTimestampToSQLTimestamp(String timeStamp) {
        return Timestamp.valueOf(timeStamp);
    }
    /**
     *
     * @param timestamp1
     * @param timestamp2
     * @return int
     */
    public static int getMinutesDiff(Timestamp timestamp1,Timestamp timestamp2) {
        long diff = timestamp1.getTime() - timestamp2.getTime();
        return Math.abs(((int)((diff / (60 * 1000) % 60))));
    }
    /**
     *
     * @param timestamp1
     * @param timestamp2
     * @return int
     */
    public static int getSecondsDiff(Timestamp timestamp1,Timestamp timestamp2) {
        long diff = timestamp1.getTime() - timestamp2.getTime();
        return Math.abs(((int)(diff / 1000 % 60)));
    }
    /**
     *
     * @param timestamp1
     * @param timestamp2
     * @return int
     */
    public static int getHoursDiff(Timestamp timestamp1,Timestamp timestamp2) {
        long diff = timestamp1.getTime() - timestamp2.getTime();
        return Math.abs(((int)(diff / (60 * 60 * 1000))));
    }
    /***
     * You need to define the date format.
     * @param timeStamp
     * @param dateFormat
     * @return java.sql.Timestamp
     * @throws ParseException
     */
    public static Timestamp convertyStringToTimestamp(String timeStamp,String dateFormat) throws ParseException {
        return new Timestamp(convertStringToDate(timeStamp,dateFormat).getTime());
    }
    /**
     * @param args
     */
    public static void main(String[] args) throws Exception{
        // TODO Auto-generated method stub
        //System.out.println(convertDateToTimeString(new Date(),DEFAULT_DATETIME_FORMAT));
        System.out.println(convertStringTimestampToSQLTimestamp("2013-05-11 06:53:48"));
        System.out.println(new Timestamp(convertStringToDate("11-May-13 06:53:48 PM +05:30",DEFAULT_DATETIME_MONTH_IN_CHAR_FORMAT).getTime()));
        Date diff1 = convertStringToDate("11-05-13 06:59:48",DEFAULT_DATETIME_FORMAT);
        Date diff2 = convertStringToDate("11-05-13 06:50:48",DEFAULT_DATETIME_FORMAT);
        System.out.println(getHoursDiff(convertStringTimestampToSQLTimestamp("2013-05-11 05:50:40"),
                convertStringTimestampToSQLTimestamp("2013-05-11 06:59:48")));
    }

}

 
BYTE CODE EXAMPLE:-
FileInputStream fis = new FileInputStream("Test.TXT");
int value = 0;
byte data [] = new byte[1024];

while(value != -1) {
value = fis.read();
System.out.print(Integer.toHexString(value));
}
fis.close();
System.out.println("DD:"+data.length);

No comments:

Post a Comment