Tuesday, 31 October 2017

What is the problem with type erasure?

Type Erasure is a process, where Java Compiler replaces type with its first bound if the type parameter is bounded, or Object if the type parameter is unbounded.

Let me explain with an example,

Box.java
public class Box<T> {

    private T data;

    public Box(T data) {
        this.data = data;
    }

    public T getData() { return data; }

}

“T” is unbounded type in Box class. So Java Compiler replaces Every Occurrence of T with Object. After compilation, above class will be converted like below.


Box.java
public class Box {

    private Object data;

    public Box(Object data) {
        this.data = data;
    }

    public Object getData() { return data; }

}

let us see one more Example with bounded type.


Box.java
public class Box<T extends Integer> {

    private T data;

    public Box(T data) {
        this.data = data;
    }

    public T getData() { return data; }

}


After type Erasure, Type Parameter “T” will be converted to Integer.
Box.java
public class Box{

    private Integer data;

    public Box(Integer data) {
        this.data = data;
    }

    public Integer getData() { return data; }

}


What is the problem with type erasure?
a.   Since type erasure erase the type information, there is no way to get the type information at run time.
b.   Because of the type erasure, you may add one type of object to collection of other type. This makes the application fails at run time.
MyCollection.java
package utils;

import java.util.ArrayList;
import java.util.List;

public class MyCollection<T> {

 private List<T> myList = new ArrayList<> ();
 
 @SuppressWarnings("unchecked")
 public void addToList(Object obj){
  myList.add((T) obj);
 }
 
 public void printCollection(){
  for(T obj : myList){
   System.out.println(obj);
  }
 }
}
Test.java
package utils;

public class Test {

 public static void main(String args[]) throws CloneNotSupportedException {
  MyCollection<Integer> collection = new MyCollection<>();

  collection.addToList("krishna");
  collection.addToList(1234);
  collection.addToList(123.456);

  collection.printCollection();
 }
}

Even though I defined the collection myList is of type Integer, I can able to add all types of objects to the collection. Compiler is unable to catch this kind of problems.

How to identify above kind of problems?
Before adding the elements to the collection, we can cast the elements using ‘cast’ method of java.lang.Class. ‘cast’ method throws ‘ClassCastException’, if it is unable to cast the object to given type.

Find the below working application.

MyCollecton.java
package utils;

import java.util.ArrayList;
import java.util.List;

public class MyCollection<T> {

 private List<T> myList = new ArrayList<>();
 private final Class<T> myClass;

 public MyCollection(Class<T> myClass) {
  this.myClass = myClass;
 }

 public void addToList(Object obj) {
  myList.add(myClass.cast(obj));
 }

 public void printCollection() {
  for (T obj : myList) {
   System.out.println(obj);
  }
 }
}

Test.java
package utils;

public class Test {

 public static void main(String args[]) throws CloneNotSupportedException {
  MyCollection<Integer> collection = new MyCollection<>(Integer.class);

  collection.addToList("krishna");
  collection.addToList(1234);
  collection.addToList(123.456);

  collection.printCollection();
 }
}


When you ran above program, you will end up in below error.

Exception in thread "main" java.lang.ClassCastException: Cannot cast java.lang.String to java.lang.Integer
    at java.lang.Class.cast(Unknown Source)
    at utils.MyCollection.addToList(MyCollection.java:16)
    at utils.Test.main(Test.java:8)

You may like

Monday, 30 October 2017

Implement case insensitive map

Implement a map that satisfies below conditions.
a.   It should treat keys case insensitively. For example, the key "India", "INDIA", "inDIA" are treated as equal and there is only one entry exist for the keys "India", "INDIA", "inDIA" at any point of time.
b.   It should return the key as it is (do not convert key to lower case (or) upper case while storing)
c.   Maintain the order of insertion.
d.   If the key is not a string, then it should behave like normal map

Before going to read the solution, I would recommend you to go through ‘How HashMap works in Java?’, ‘How LinkedHashMap works in Java?’, ‘How TreeMap works in Java?’

All the crud specific methods like get, put, putAll, containsKey, remove, entrySet, keySet is going to be impacted to implement a map case sensitively.

While inserting a key into the map, we should check whether the key is instance of string or not. If key is instance of string, we need to check, whether any case-insensitive string present or not. If the case insensitive string is already existed in the map, then we should replace that entry with given entry.

There can be multiple implementations possible, but I would like to go with below approach.

I defined new class ‘CaseInsensitiveString’ to wrap string keys.
 private static class CaseInsensitiveString {
  private String key;

  public CaseInsensitiveString(String key) {
   this.key = key;
  }

  @Override
  public int hashCode() {
   if (key == null)
    return 0;

   return key.toUpperCase().hashCode();
  }

  @Override
  public boolean equals(Object obj) {
   if (this == obj)
    return true;
   if (obj == null)
    return false;
   if (getClass() != obj.getClass())
    return false;
   CaseInsensitiveString other = (CaseInsensitiveString) obj;
   if (key == null) {
    if (other.key != null)
     return false;
   } else if (!key.toUpperCase().equals(other.key.toUpperCase()))
    return false;
   return true;
  }

  @Override
  public String toString() {
   return key;
  }

 }


If the key is of type string, then I will wrap the string using CaseInsensitiveString object. I override the hashCode and equals method such that, two case-insensitive equal strings always point to same bucket and treated as equal. If you would like to know the relation between equals and hashCode method, I would recommend you to go through ‘Contract between hashCode and equals’.

To satisfy the point c, we should use the LinkedHashMap.

Find the below working application, java documentation on the methods is self-explanatory.


InsensitiveMap.java

package com.sample.collections;

import java.util.AbstractMap;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;


public class InsensitiveMap<K, V> implements Map<K, V> {
 private Map<K, V> map;

 public InsensitiveMap() {
  map = new LinkedHashMap<>();
 }

 /**
  * Convert the object to Case insensitive string.
  * 
  * @param obj
  * @return
  */
 private static CaseInsensitiveString convertObjectToCaseInsensitiveString(Object obj) {
  String keyStr = (String) obj;
  return new CaseInsensitiveString(keyStr);
 }

 @Override
 public int size() {
  return map.size();
 }

 @Override
 public boolean isEmpty() {
  return map.isEmpty();
 }

 @Override
 public boolean containsKey(Object key) {
  if (!(key instanceof String)) {
   return map.containsKey(key);
  }

  return map.containsKey(convertObjectToCaseInsensitiveString(key));
 }

 @Override
 public boolean containsValue(Object value) {
  return map.containsValue(value);
 }

 @Override
 public V get(Object key) {
  if (!(key instanceof String)) {
   return map.get(key);
  }

  return map.get(convertObjectToCaseInsensitiveString(key));
 }

 @Override
 public V put(K key, V value) {
  if (!(key instanceof String)) {
   return map.put(key, value);
  }

  CaseInsensitiveString caseInsensitiveString = convertObjectToCaseInsensitiveString(key);
  return map.put((K) caseInsensitiveString, value);

 }

 @Override
 public V remove(Object key) {
  if (!(key instanceof String)) {
   return map.remove(key);
  }

  return map.remove(convertObjectToCaseInsensitiveString(key));

 }

 @Override
 public void putAll(Map<? extends K, ? extends V> m) {
  if (m == null) {
   return;
  }

  for (Entry<? extends K, ? extends V> entry : m.entrySet()) {
   put(entry.getKey(), entry.getValue());
  }
 }

 @Override
 public void clear() {
  map.clear();
 }

 @Override
 public Set<K> keySet() {

  Set set = new LinkedHashSet();

  for (Object key : map.keySet()) {
   set.add(key instanceof CaseInsensitiveString ? key.toString() : key);
  }
  return set;
 }

 @Override
 public Collection<V> values() {
  return map.values();
 }

 @Override
 public Set<java.util.Map.Entry<K, V>> entrySet() {
  Set<Entry<K, V>> entrySet = map.entrySet();
  Set<Entry<K, V>> outputSet = new LinkedHashSet<Entry<K, V>>();

  for (Entry entry : entrySet) {
   if (!(entry.getKey() instanceof CaseInsensitiveString)) {
    outputSet.add(entry);
   }

   CaseInsensitiveString key = (CaseInsensitiveString) entry.getKey();
   entry = new AbstractMap.SimpleImmutableEntry<K, V>((K) key.toString(), (V) entry.getValue());

  }

  return outputSet;
 }

 private static class CaseInsensitiveString {
  private String key;

  public CaseInsensitiveString(String key) {
   this.key = key;
  }

  @Override
  public int hashCode() {
   if (key == null)
    return 0;

   return key.toUpperCase().hashCode();
  }

  @Override
  public boolean equals(Object obj) {
   if (this == obj)
    return true;
   if (obj == null)
    return false;
   if (getClass() != obj.getClass())
    return false;
   CaseInsensitiveString other = (CaseInsensitiveString) obj;
   if (key == null) {
    if (other.key != null)
     return false;
   } else if (!key.toUpperCase().equals(other.key.toUpperCase()))
    return false;
   return true;
  }

  @Override
  public String toString() {
   return key;
  }

 }

}


Test.java

package com.sample.collections;

import java.util.Map;
import java.util.Set;

import com.sample.collections.InsensitiveMap;

public class Test {

 private static void printMap(Map map) {

  Set set = map.keySet();

  for (Object obj : set) {
   System.out.println(obj + " " + map.get(obj));
  }
 }

 public static void main(String args[]) throws CloneNotSupportedException {
  InsensitiveMap<String, String> map = new InsensitiveMap<>();

  map.put("Krishna", "ptr");

  printMap(map);

  map.put("KRIshna", "123");
  printMap(map);

  map.put("KRISHNA", "abcde");
  printMap(map);

 }
}


Output

Krishna ptr
Krishna 123
Krishna abcde



Tuesday, 24 October 2017

How to get shallow copy of array?

clone() method of array return the shallow copy of this array.

Test.java
public class Test {

 public static void printArray(int[] arr) {
  for (int data : arr) {
   System.out.print(data + " ");
  }
 }

 public static void main(String args[]) {
  int[] arr1 = { 2, 3, 5, 7 };
  int[] arr2 = arr1.clone();

  System.out.println("Elements in arr1 are :");
  printArray(arr1);

  System.out.println("\nElements in arr2 are :");
  printArray(arr2);
 }
}


How shallow copy works on reference types?
A shallow copy just copies the values of the references. Lets see it by an example.


Lets take a Student class, which contains 'marks' object and two fields(name, id).
If we clone Student s1 as Student s2. Then fields other than reference variables are copied as separate variables, but the reference variable 'marks' is same for both student s1 and s2. I.e, a shallow copy just copies the values of the references in the class. So changes to the marks object by student s1 is reflected to s2 and vice versa.
Find the below working application.

Marks.java
package com.sample.model;

public class Marks {
 public int maths, physics, chemistry;

 public Marks(int m, int p, int c) {
  maths = m;
  physics = p;
  chemistry = c;
 }
}

Student.java
package com.sample.model;

public class Student implements Cloneable {
 public int id;
 public String name;
 public Marks marks;

 public Student(int id, String name, Marks marks) {
  this.id = id;
  this.name = name;
  this.marks = marks;
 }

 public void printMarks() {
  System.out.println("Maths: " + marks.maths);
  System.out.println("Physics: " + marks.physics);
  System.out.println("Chemistry: " + marks.chemistry);
 }

 @Override
 public String toString() {
  return id + "." + name;
 }

 @Override
 public Object clone() throws CloneNotSupportedException {
  return super.clone();
 }
}

Test.java
package utils;

import com.sample.model.Marks;
import com.sample.model.Student;

public class Test {

 public static void main(String args[]) throws CloneNotSupportedException {
  Marks m1 = new Marks(95, 96, 75);

  Student s1 = new Student(1, "Krishna", m1);
  Student s2 = (Student) s1.clone();

  System.out.println("For student s1");
  System.out.println(s1);
  s1.printMarks();

  System.out.println("\n\nFor student s2");
  System.out.println(s2);
  s2.printMarks();

  System.out.println("\nchange marks of student s2 to 35, 45, and 55");
  s2.marks.maths = 35;
  s2.marks.physics = 45;
  s2.marks.chemistry = 55;

  System.out.println("Change the name to hari and id to 2 for student s2");
  s2.name = "Hari";
  s2.id = 2;

  System.out.println("\n\nFor student s1");
  System.out.println(s1);
  s1.printMarks();

  System.out.println("\n\nFor student s2");
  System.out.println(s2);
  s2.printMarks();
 }
}

Output
For student s1
1.Krishna
Maths: 95
Physics: 96
Chemistry: 75


For student s2
1.Krishna
Maths: 95
Physics: 96
Chemistry: 75

change marks of student s2 to 35, 45, and 55
Change the name to hari and id to 2 for student s2


For student s1
1.Krishna
Maths: 35
Physics: 45
Chemistry: 55


For student s2
2.Hari
Maths: 35
Physics: 45
Chemistry: 55





Monday, 23 October 2017

Delete a directory recursively in Java

In this post, I am going to show you how to delete a directory recursively in Java.

PseudoCode.
Step 1: First check whether given file exists or not.
Step 2: If file is not exist return.
Step 3: If file is a directory, then read all the children from given directory. For every children, if the children is a directory then repeat step 3 and delete the file.

Find the below working application.

FileUtil.java
package utils;

import java.io.File;

public class FileUtil {
 public static void deleteDirectory(String dirName) {
  if (dirName == null || dirName.isEmpty()) {
   throw new IllegalArgumentException("File name shouldn't be empty");
  }
  File file = new File(dirName);

  if (!file.exists()) {
   System.out.println("File is not existed");
   return;
  }

  if (file.isDirectory()) {
   deleteDirectory(file);
   file.delete();
  }

 }

 private static void deleteDirectory(File dir) {

  File[] children = dir.listFiles();

  for (File file : children) {
   if (file.isDirectory()) {
    deleteDirectory(file);
   }
   file.setWritable(true);
   file.delete();
  }

 }
}


Test.java
package utils;

public class Test {

 public static void main(String args[]) {
  String dirName = ""; // Directory absolute path to delete
  FileUtil.deleteDirectory(dirName);

 }
}