Pages

Tuesday, October 21, 2014

Serialize complete binary tree

One of the lunch table discussion....


What if I want to store whole binary tree into file?
I said, implement serializable interface for Node and you are good to go, person was not convinced, I have to saw him actual implementation. Here is my sample code. Normally people make assumption that only given node will be stored and not whole tree, which is not true. Serialization takes care of whole tree. Sample code below:

Node.java


package com.java;
import java.io.Serializable;


public class Node implements Serializable {
 private static final long serialVersionUID = 1L;
 
 public int data;
 public Node left;
 public Node right;
 
 public Node(int data, Node left, Node right) {
  super();
  this.data = data;
  this.left = left;
  this.right = right;
 }
 
 public Node(int data) {
  this(data, null, null);
 }

  public Node() {
  super();
 }
}

SerializeDeserializeBT.java

package com.java;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;


public class SerializeDeserializeBT implements Serializable {

  public static void main(String[] args) {
  SerializeDeserializeBT s = new SerializeDeserializeBT();
  
  Node root = s.initBTree();
  s.serialize(root);
  s.deserialize();
 }

  public Node initBTree() {
  
  return new Node(80, new Node(60, new Node(50), new Node(70)), new Node(86, new Node(82), new Node(90)));

  }

  public void serialize(Node root){

  try {
   FileOutputStream fs = new FileOutputStream("C:\\test.ser");
   ObjectOutputStream os = new ObjectOutputStream(fs);
   os.writeObject(root);
   os.close();
   fs.close();
   
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 public void deserialize() {
  try {
   FileInputStream fis = new FileInputStream("c:\\test.ser");
   ObjectInputStream input = new ObjectInputStream(fis);
   
   Node root = (Node) input.readObject();
   
   traverseInOrder(root);
  } catch(Exception e) {
   e.printStackTrace();
  }
 }
 
 public void traverseInOrder(Node root) {
  if(root != null) {
   traverseInOrder(root.left);
   System.out.println(root.data + " " );
   traverseInOrder(root.right);

   }
 }
}

Inorder Traversal of two binary trees

Problem Description:
Write a program to print inorder traversal of two trees.  Both values must be printed alternatively. 

e.g. if inorder traversal of tree 1 is 10, 15, 20 and tree 2 is 100, 150, 200 then it should print  10, 100, 15, 150, 20, 200. 

Solution:
I used threads to keep track of printing one by one thread, it uses recursive inorder traversal synchronized block. 

Assumptions: 
Tree need not to be same level - meaning both tree can hold different number of nodes and can differ in number of levels.




package com.java;
import java.io.Serializable;

Node.java
public class Node {
 
 public int data;
 public Node left;
 public Node right;
 
 public Node(int data, Node left, Node right) {
  super();
  this.data = data;
  this.left = left;
  this.right = right;
 }
 
 public Node(int data) {
  this(data, null, null);
 }

  public Node() {
  super();
 }
}

public static void main(String[] args) {
  
 Thread t1 = new Thread() {
  public void run() {
   TreeCheck tc = new TreeCheck();
   Node tree1 = new Node(20, new Node(10), new Node(40, new Node(30), null));
   tc.inOrder(tree1);
  }
 };
 Thread t2 = new Thread() {
  public void run() {
    TreeCheck tc = new TreeCheck();
    Node tree2 = new Node(80, new Node(60, new Node(50), new Node(70)), new Node(86, new Node(82), new Node(90)));
    tc.inOrder(tree2);
  }
 };
 
 t1.start();
 t2.start();
  
 }
 
 public void inOrder(Node root) {
  
  if(root.left != null){
   inOrder(root.left);
  }
  
  synchronized(this) {
   System.out.println(root.data);
   try {
    Thread.sleep(2000);
   } catch(Exception e) {
    e.printStackTrace();
   }
  }
  
  if(root.right != null){
   inOrder(root.right);
  }
 }
}

Friday, July 12, 2013

Method Overriding and Covariant Return Type

While refreshing my concepts on method overriding, I came across something called "covariant return type" - I was amazed that even though I used it multiple times - but I never cared about terminology used here. Normally method overriding is achieved by redefining an inherited method to serve a different functionality, which indirectly covers parameter list (method arguments) and return type. 

Here when we talk about Covariant return type which I believe a corner case (of course a very useful) where only return type changes in a specific scenario and condition is if return type of subclass overriding method has to be subclass type or in other worlds one can change only return type of overriding method as long as return type is subclass type. I suggest read the previous sentence once again, very carefully if you are not clear about the idea.

Lets take an example to understand it a bit better:


public class SimpleDataProvider {
 public SimpleDataProvider getProvider() {
  return this;
 }
}

public class XMLDataProvider extends SimpleDataProvider{
 //As you know that getData method is available as a part of inheritance.
 //Now overriding with covariant return type as follows
 
 public XMLDataProvider getProvider(){
  return new XMLDataProvider();
 }
 
 public void printXMLDataProvider(){
  System.out.println("SampleXML Data");
 }
}

public class TestCovariantReturnType {
 public static void main(String args[]) {
  new XMLDataProvider().getProvider().printXMLDataProvider();
 }
}

In the above example as you can see Overridden method getProvider only changes return type (and no changes in argument list) - but still its allowed and valid.

I hope it helps...If I revisit..I will put a better example/explanation here.

Importance of serialVersionUID?

Below post is more useful to myself for knowledge brushup..From docs for java.io.Serializable:


The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender’s class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named “serialVersionUID” that must be static, final, and of type long:
static final long serialVersionUID =653553563546L;  
If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class–serialVersionUID fields are not useful as inherited members

Tuesday, March 19, 2013

How recollect Comparable and Comparator..Its made easy


Even though I have used Comparable and Comparator methods on various occations and used it meaningfully still sometimes it was hard to recollect which characterstics belong to which one.

Then slowly I developed a technique to remember it - 

Here is how:

Comparabl'e' Comparato'r'
I remember ending e......and ending r

When I face 'e' - I see its one argument
When I face 'r' - I see its multiple argument

With above half of my problem is solved....

Next part is method names:

compareTo - from the name I can figure out that it has compare one object with another (which is passed as argument)

On the other side, compare method, where I have to pass two objects as an argument for making comparison between them.

Putting together

ComparableOne ArgumentcompareTo method
ComparatorTwo Argumentscompare method

Both compareTo and compare methods returns integer values. 
-ve if right is greater than left, zero if both are equal and +ve if left is greater than right

How is it now? Simple or??

Twisted mixture of Overloaded and Overridden Method

While referring concepts of method overloading and overriding I came across a wired combination where correct and deep understanding really helps to do good quality software development and avoid falling into trap while dealing with such code base - whether its for real life projects, learning, certification, quiz or just simple knowledge sharing talks.

I would like to start it with simple real life example


1:  public class File {  
2:       public void open() {  
3:            System.out.println("Simple File Open..");  
4:       }  
5:  }  
6:    
7:  public class XMLFile extends File {  
8:       public void open() {  
9:            System.out.println("XML File Open..");  
10:       }  
11:         
12:       //parseXML is additional method which is not available in File Class  
13:       public void parseXML() {  
14:            System.out.println("Parse XML File..");  
15:       }  
16:  }  
17:    
18:  //Test Program for Overriding  
19:    
20:  public class MyTestFile {  
21:       public static void main(String args[]){  
22:              
23:            //Objects with Reference Type and Object Type same.  
24:            File simpleFile1 = new File();  
25:            XMLFile xmlFile1 = new XMLFile();  
26:              
27:            //Its very clear what will be printed from following code  
28:            simpleFile1.open();  
29:            xmlFile1.open();  
30:              
31:            //Trap 1 - Still Managable  
32:            File xmlFile2 = new XMLFile();  
33:              
34:            //Following will call XMLFile.open version and NOT File.open   
35:            xmlFile2.open();  
36:              
37:            //Trap 2 - Little Twist  
38:            xmlFile2.parseXML(); //Fail to compile...you know why because its not available with File class - so one can not invoke it.  
39:              
40:            //Trap 3 - Real Confusion Occurs here..  
41:            //Adding Overloaded methods  
42:              
43:            public void OrganizeFile(File file){  
44:                 System.out.println("Organizing Simple File..");  
45:            }  
46:              
47:            public void OrganizeFile(XMLFile xmlFile){  
48:                 System.out.println("Organizing Simple File..");  
49:            }  
50:              
51:            //Here is a magic  
52:            MyTestFile testFile = new MyTestFile();  
53:            testFile.OrganizeFile(simpleFile1); //No Issues  
54:            testFile.OrganizeFile(xmlFile1); //No Issues  
55:              
56:            //Assume which one will be called here..?? Based on Trap-2 you will say obviously xmlversion..but NO  
57:            //It will Call File Version and not XMLFile Version...why? ..Check the explanation  
58:            testFile.OrganizeFile(xmlFile1);  
59:       }  
60:  }  
Explanation:
In Java choice of which ovarloaded method to call is NOT dynamically decided at runtime. Meaning reference type (not the object type) determines which overloaded method is invoked. 

In short, which overridden version of the method to call is decided at runtime based on object type, but which overloaded version of the method to call is based on the reference type of the argument passed at compile time. 


I Hope this helps!! 
Thank You.

Tuesday, October 9, 2012

Java Internationalization (I18N)

Java Internationalization (I18N)

To get the output in various languages java.util.Locale is used. You also need to provide corresponding properties file for languages supported by you application. Here you will see I have provided default, German (de), Franch (fr) properties file.

I18N_Example.java
package com.manan.testlab;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;

public class I18N_Example {


public static void main(String[] args) {
String name = "com.manan.testlab.Manan";
ResourceBundle rb;

rb = ResourceBundle.getBundle(name);
System.out.println(rb.getString("Hello" + ".text"));

rb = ResourceBundle.getBundle(name, Locale.GERMANY);
System.out.println(rb.getString("Hello" + ".text"));

rb = ResourceBundle.getBundle(name, Locale.CHINA);
System.out.println(rb.getString("Hello" + ".text"));

Locale[] locales = new Locale[] {
                Locale.JAPAN,
                Locale.CHINA,
                Locale.KOREA,
                Locale.TAIWAN,
                Locale.ITALY,
                Locale.FRANCE,
                Locale.GERMAN
        };

Date today = new Date();

for (Locale locale : locales) {
            System.out.println("Date format in "
                + locale.getDisplayName() 
                + " = "
                + SimpleDateFormat.getDateInstance(
                      SimpleDateFormat.LONG, locale)
                          .format(today).toUpperCase());
        }
}
}

Manan.properties
Hello.text=Hello..

Manan_de.properties
Hello.text=DE_Hello In German..

Manan_fr_FR.properties
Hello.text=Bonjour


File List Sorting based on sorting parameter

Problem Definition:
For a given file list with properties like FileName, Location, DateCreation, DeteModification, Type - sort it based on supplied argument - in other words implement functionality of applying sort mechanism (windows) based on headers clicked.

SortingFileList.java


package com.manan.testlab;

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

public class SortingFileList {

public static void main(String[] args) {
List<File> fileList = new ArrayList<File>();

File f1 = new File("f1","c:\\", new Date(new Long(1018024496)), new Date(1018024498), "txt");
File f2 = new File("a1","d:\\", new Date(new Long(1018024500)), new Date(1018024510), "zip");
File f3 = new File("z1","c:\\", new Date(1018024510), new Date(1018024580), "jar");
File f4 = new File("c1","d:\\", new Date(1018024610), new Date(1018024810), "jar");
File f5 = new File("a2","d:\\", new Date(new Long(1016024500)), new Date(1018024910), "doc");

fileList.add(f1);
fileList.add(f2);
fileList.add(f3);
fileList.add(f4);
fileList.add(f5);

FileName fn = new FileName();

// Comment/Uncomment following to verify based on location, date creation type
// FileLocation fn = new FileLocation();
// FileCreationDate fn = new FileCreationDate();
// FileType fn = new FileType();
Collections.sort(fileList, fn);

//Display Arraylist
for(int i=0;i<fileList.size();i++){
System.out.println(fileList.get(i).toString());
}
}
}

File.java

package com.manan.testlab;

import java.text.Collator;
import java.util.Comparator;
import java.util.Date;

public class File {
String name;
String location;
Date dateCreation;
Date dateModified;
String type;
public File(String name, String location, Date dateCreation,
Date dateModified, String type) {
super();
this.name = name;
this.location = location;
this.dateCreation = dateCreation;
this.dateModified = dateModified;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public Date getDateModified() {
return dateModified;
}
public void setDateModified(Date dateModified) {
this.dateModified = dateModified;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}

@Override
public String toString() {
return "File [name=" + name + ", location=" + location
+ ", dateCreation=" + dateCreation + ", dateModified="
+ dateModified + ", type=" + type + "]";
}
}

//IMPORTANT
class FileName implements Comparator<File>{
public int compare(File left, File right){
return left.getName().compareTo(right.getName());
// Get the list in reverese order (Z-A)
// return right.getName().compareTo(left.getName());
}
}

class FileLocation implements Comparator<File>{
public int compare(File left, File right){
return left.getLocation().compareTo(right.getLocation());
}

class FileCreationDate implements Comparator<File>{
public int compare(File left, File right){
return left.getDateCreation().compareTo(right.getDateCreation());
}
}

class FileModificationDate implements Comparator<File>{
public int compare(File left, File right){
return left.getDateModified().compareTo(right.getDateModified());
}
}

class FileType implements Comparator<File>{
public int compare(File left, File right){
return left.getType().compareTo(right.getType());
}
}

Output:
File [name=a1, location=d:\, dateCreation=Tue Jan 13 00:17:04 IST 1970, dateModified=Tue Jan 13 00:17:04 IST 1970, type=zip]
File [name=a2, location=d:\, dateCreation=Mon Jan 12 23:43:44 IST 1970, dateModified=Tue Jan 13 00:17:04 IST 1970, type=doc]
File [name=c1, location=d:\, dateCreation=Tue Jan 13 00:17:04 IST 1970, dateModified=Tue Jan 13 00:17:04 IST 1970, type=jar]
File [name=f1, location=c:\, dateCreation=Tue Jan 13 00:17:04 IST 1970, dateModified=Tue Jan 13 00:17:04 IST 1970, type=txt]
File [name=z1, location=c:\, dateCreation=Tue Jan 13 00:17:04 IST 1970, dateModified=Tue Jan 13 00:17:04 IST 1970, type=jar]

Tuesday, October 2, 2012

Spiral Matrix Problem

Problem Definition: Display/Construct n*n matrix in Spiral Form for eg: 3*3 matrix

Input            Output
1  2  3          1  2  3
4  5  6          8  9  4
7  8  9          7  6  5
Solution:

public class SprialMatrixProblem {
static int input = 4;
static int[][] matrix = new int[input][input];
static int counter = 1;

public static void main(String args[]){
SprialMatrixProblem.moveRightDown(0, -1, input);
SprialMatrixProblem.displayMatrix();
}


public static void moveRightDown(int iStart, int jStart, int matrixSize){
if(matrixSize > 0){
for(int j=0;j<matrixSize;j++){
jStart++;
matrix[iStart][jStart] = counter;
counter++;

}

matrixSize--;

for(int i=0;i<matrixSize;i++){
iStart++;
matrix[iStart][jStart] = counter;
counter++;
}

SprialMatrixProblem.moveLeftUp(iStart, jStart, matrixSize);
}
}

public static void moveLeftUp(int iStart, int jStart, int matrixSize){
if(matrixSize > 0){
for(int j=0;j<matrixSize;j++){
jStart--;
matrix[iStart][jStart] = counter;
counter++;
}

matrixSize--;

for(int i=0;i<matrixSize;i++){
iStart--;
matrix[iStart][jStart] = counter;
counter++;
}

SprialMatrixProblem.moveRightDown(iStart, jStart, matrixSize);
}
}

public static void displayMatrix(){
for(int i=0;i<input;i++){
for(int j=0;j<input;j++){
System.out.println(matrix[i][j] + " ");
}
}
}
}