Tuesday, June 25, 2013

Java : General purpose Implementation Classes in Collection Framework


Collection framework consists of general purpose implementation of Set, Map, List interfaces.
Details of Interfaces in Collection framework is available at Collection Framework Interfaces
Main characteristics of General purpose implementation in Collection framework is described as below.

HashSet:
  • Extends AbstractSet, implements Set, Cloneable, Serializable.
  • Implements Set interface backed by HashMap instance.
  • Null element is allowed.
  • Unordered collection.
  • Default initial capacity of 16 and load factor of 0.75.
  • Constant time performances for basic operations (add, remove, size, contains).
  • Iterating over set requires time proportional to number of elements in Set and capacity of backing HashMap instance.
  • Not synchronized.
  • Iterator returned by this class is fail-fast. If set is modified after iterator is created, iterator throws ConcurrentModificationException.

TreeSet:
  •  Extends AbstractSet, implements NavigableSet, Cloneable, Serializable
  • Implementation is based on TreeMap.
  • Elements are ordered by natural order or by Comparable provided at the time of creation of Set.
  • Not synchronized.
  • Null is not allowed.
  • Iterator returned by this class is fail-fast. If set is modified after iterator is created, iterator throws ConcurrentModificationException.
  • There are methods available to get subset of existing Set. Subset is backed by original Set, so any addition of element within range to set will be reflected to Subset and vice-versa.
    • subset(fromElement, toElement) - fromElement is inclusive and toElement is excluded
    • subSet(fromElement,  boolean fromInclusive, toElement, boolean toInclusive) –using Boolean fromElement and toElement can be made inclusive or excluded.

ArrayList:
  • Extends AbstractList, implements List, Cloneable, Serializable, RandomAccess.
  • Random access of elements is fast compared to LinkedList.
  • Element are stored in sequence in array.
  • Null is allowed.
  • Not synchronized.
  • Iterator returned by this class is fail-fast. If set is modified after iterator is created, iterator throws ConcurrentModificationException.
  • ArrayList has capacity which is size of array to store objects. ensureCapacity  method is used to make sure that size of ArrayList is appropriate.
  • Default initial capacity is 10.


LinkedList:
  • Extends AbstractSequentialList, implements List, Deque, Cloneable, Serializable.
  • Null is allowed.
  • Methods available to add, remove, get element at the beginning and end of the list.
  • Not synchronized.
  • Iterator returned by this class is fail-fast. If set is modified after iterator is created, iterator throws ConcurrentModificationException.

  
HashMap:
  • Extends AbstractMap, Implements Map, Serializable, Cloneable.
  • HashMap allows one null key
  • Not synchronized.
  • Iterator returned by this class is fail-fast. If set is modified after iterator is created, iterator throws ConcurrentModificationException.
  • HashMap has two parameters – Initial capacity and load factor which affects performance.
  • Default initial capacity 16
  • Default load factor 0.75
  • Rehashing is done when capacity/load factor is more than number of elements in HashMap.

Wednesday, June 19, 2013

Java : Interfaces in Collection Framework

Collection Interfaces:

  •  Collection
  • Set
    •    SortedSet
    •    NavigableSet
  • List
  • Queue
    •  BlockingQueue
    • TransferQueue
    • Deque
  • Map
    • SortedMap
    • NavigableMap
    • ConcurrentMap
    • ConcurrentNavigableMap

Main interfaces:
  • Collection:
    • Root interface in Collection hierarchy. It represents group of objects. Java does not provide direct implementation of this interface. It provides implementation of more specific interfaces by extending this interface like Set, List.
    • This interface defines basic operations for group of objects.
    • There are also some methods which are tagged as optional operations which may not be applicable for specific type of collection. E.g. For read only collections, add(E), remove(Object) methods are not required, so implementation classes may just throw UnsupportedOperationException in method implementation.  If the invocation would have no effect on the collection, then it may or may not throw exception.
  • Set:
    • Collection that contains no duplicate elements and at most one null element. (some implementations does not allow null)
    • You have to be careful when mutable objects are added as elements of set. Set behaviour is not specified if value of object which is in set is changed which affects equals comparison.
    • Set provides additional constraint on add method to prevent duplicates.
  • List:
    • List is ordered collection. List may contain duplicates.
    • List provides special iterator, called ListIterator, which allows element insertion, bidirectional access.
    • List provides additional constraint over iterator, add, remove methods to maintain sequence of elements.
  • Queue:
    • Queue typically, but not necessarily, order elements in FIFO manner. Among the exceptions are priority queues, which order elements according to a supplied comparator or the elements' natural ordering, and LIFO queues (or stacks) which order the elements LIFO (last-in-first-out)
    • Queue provides additional methods for insertion, removal, inspection operations which returns special value (null or false) if operation fails. Collection methods add, remove, element throws exception if method fails.
    • Queue generally does not allow null. (Except LinkedList). Null should not be inserted into queue because null is returned by poll method to indicate that queue is empty.
  • Map:
    • Object that contains key-value pair. Map interface does not extends Collection.
    • Map cannot contain duplicate key. So special care should be taken when mutable objects are used as keys.

Additional Interfaces:


  • SortedSet:
    • Ordered collection.
    • Elements are by default in natural order or as per Comparator provided at creation time.
    • All elements inserted into a sorted set must implement the Comparable interface.
    • General implementation of SortedSet should provide 4 standard constructors.
      • Void constructor with no parameter
      • Constructor with parameter as Comparator
      • Constructor with parameter as Collection
      • Constructor with parameter as SortedSet
  • NavigableSet:
    • It extends SortedSet and provides navigation methods to find closest match for given target.
    • Navigation methods are lower, floor, ceiling, higher.
    • pollFirst and pollLast methods that return and remove the lowest and highest element, if one exists, else returning null.
  • Deque:
    • Double ended queue. Extends Queue.
    • Element insertion and removal at both ends.
    • Interface defines methods (add, remove, get) to access elements at both end of queue. All methods have 2 forms. One throws exception if operation fails and other returns special value (null or false).
  • BlockingQueue:
    • Interface of concurrent package. Use for Producer-Consumer type operation.
    • While inserting element in queue, it waits if for space to be available when queue is full.
    • While retrieving element from queue, it waits if queue is empty.

Friday, June 14, 2013

Java Collection Framework Basic

Java collection framework and its classes are used to store and process group of objects.

Advantages of Collection framework:
  •  Reduces programming effort: Useful data structures and utility classes to process data for searching/sorting etc. are readily available in Collection framework.
  •   Provides inter- operability between API’s: Collection objects are used to pass/return to different API methods instead of creating different data structures for each API.
  • Increased performance: High performance implementation of data structure in Collection framework.

  
Collection framework consists of:
  1. Collection Interfaces: Different type of collection interfaces like set, map, list, queue.
  2. Collection implementation classes: Different type of concrete implementations of collection interfaces.
  3. Concurrent implementation: Implementations for concurrent use.
  4. Algorithms: Utility classes with methods to do searching, sorting operations.


Thursday, June 13, 2013

Java: Storing null key in HashMap

HashMap is useful in searching exact data in short time.
HashMap allows only one null key. Let's see how it stores null key internally.

If key is null, HashMap allows putting single value against null key. 
If you are trying to add another value against null key, it returns existing value for null key and stores new value against null key.
Internally HashMap maintains array of Entry class(internal class of HashMap which is used to store data) which is also called as Bucket.
Entry class contains key, value, nextElement, hash-value variables.

Data with null key is stored at Bucket location 0(array index 0 of Entry array). Hash value is also zero for null key.

Example:
HashMap h = new HashMap();  You can also use HashMap instead of HashMap.
h.put(null, "A");         -- Value "A" is stored against null key
h.put(null, "B");         -- Value "B" is stored against null key and old value "A" is returned as return type of put function is V i.e. value object
h.put(null, "C");         -- Value "C" is stored against null key and old value "B" is returned 



Wednesday, June 5, 2013

Sample Hibernate Application Using Eclipse and using annotations

In first example, I have created sample Hibernate project using mapping files
Next step is to convert same application to use annotations.
Change Employee.java and Department.java files to use annotations as shown below.

Employee.java

package com.test.beans;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="EMP")
public class Employee {
@Id @GeneratedValue
@Column(name="emp_id")
private Long empId;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column(name="degn")
private String designation;
@Column(name="sal")
private double salary;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="dept")
private Department dept;
public Long getEmpId() {
return empId;
}
public void setEmpId(Long empId) {
this.empId = empId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Department getDept() {
return dept;
}
public void setDept(Department dept) {
this.dept = dept;
}
}

Department.java:

package com.test.beans;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="DEPT")
public class Department {
@Id @GeneratedValue
@Column(name="dept_id")
private long deptId;
@Column(name="dept_name")
private String deptName;
@Column(name="loc")
private String location;
public long getDeptId() {
return deptId;
}
public void setDeptId(long deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}

Change hibernate.cfg.xml file as:

  <? xml version="1.0" encoding="UTF-8"?>


<!

DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD/EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >


<hibernate-configuration>



<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hibernate.use_sql_comments">true</property>

<mapping class="com.test.beans.Employee" />
<mapping class="com.test.beans.Department" /> 
</session-factory>
</hibernate-configuration>


You can delete (organization.hbm.xml) hbm mapping file.

Now your sample annotation project is ready. You can run Test.java file to check the output.

Sunday, June 2, 2013

Automatic Dirty checking and Transaction write-behind concepts of Hibernate

Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transaction write-behind.

Automatic Dirty checkingIf object which is already saved is modified, then Hibernate automatically call update on that object.
Hibernate is capable of detecting all objects that are modified or are dirty. It is done with the help of PersistanceContext.
Within PersistanceContext, Hibernate has copy of all persistent objects that are loaded from database in Session. It compares persistent object to determine whether object is modified.


Hibernate allows implementation of custom dirty checking algorithm. This is done by implementing findDirty() method of org.hibernate.Interceptor interface for a Session.