Wednesday, September 27, 2017

React 16.0 released

React 16.0 is released today which is built on top of new core architecture named 'Fiber'.
Most importantly, they are not breaking backward compatibility like what Angular did while releasing 2.0.
They are now using MIT open source licence so all the confusion around licencing issues is gone.

Here is a link which gives detailed overview of the release.

Monday, September 11, 2017

Java 9 releasing on 21 September 2017

After postponing release many times, finally Java 9 will be releasing on 21 September 2017.
It is much awaited release of Java as there are many structural changes coming with this release in platform.
Java 9 is Modular Java.
Pre-general availability documentation is available on Oracle website.

Link to documentation:
https://docs.oracle.com/javase/9/whatsnew/toc.htm#JSNEW-GUID-C23AFD78-C777-460B-8ACE-58BE5EA681F6

More details about Java 9 project is available at:
http://openjdk.java.net/projects/jdk9/

Java 9 is finally released and JDK download link is:
http://www.oracle.com/technetwork/java/javase/downloads/jdk9-downloads-3848520.html

Sunday, September 10, 2017

Interceptor for Spring Rest controller

Create a java class which extends HandlerInterceptorAdapter.
You can override preHandle and postHandle methods as per your requirement.

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("In Prehandle");
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    System.out.println("In postHandle");
}

In spring-mvc-context.xml file, define class as interceptor as

 
  

Now your interceptor class should intercept all requests towards Rest controller. 

Sunday, July 30, 2017

Amazon Web Services - Getting started

Registration:

  • After filling basic information, you need to fill billing information (Credit card details) during the registration process.
  • After entering billing information, Transaction of Rs. 2 will be initiated to verify your Billing details (Transaction will be cancelled later by Amazon automatically).
  • Verification of Phone/Mobile with Automated Call.
  • Post verification, your account will be created.

Getting Started with Amazon Web Service Cloud:
  • On AWS dashboard, there are different options to start with, Choose - Launch a Virtual Machine option

  • Type Name for your instance.
  • There will be option to download private key to connect to instance.
  • Download private key(*.pem format)
  • After you submit, your instance will be launched successfully.
  • You can view the instance from Instances option of EC2 Dashboard.


Connecting to Virtual Machine using Putty:
  • You need to generate private key using PuttyGen application.
  • Load your_key.pem in PuttyGen by clicking Load button.
  • Click on generate private key button. (It will warning message to save key without passcode. Select Yes).
  • Save the private key (format *.ppk)
  • Open Putty terminal window.
  • Default user for VM is "ec2-user".
  • Check Public DNS of your Virtual machine on EC2 dashboard. Format of DNS is like ëc2-*-2.compute.amazonaws.com
  • Enter hostname as : ec2-user@public-DNS of your VM. - ec2-user@ec2-*-us-east-2.compute.amazonaws.com
  • Enter port as 22.
  • Open SSH tab on left and on Auth tab - Select private key file as *.ppk file which is generated using PuttyGen tool.
  • Click on Open. You should be able to connect to Virtual Machine.
TroubleShooting while connecting to VM:
  • By default, IP address for Inbound connections on VM is the one from which you have created Virtual Machine and it is managed by Security Groups.
  • Check which Security Group is assigned to your VM in Description at the bottom.
  • View Inbound Rules - Set source IP as 0.0.0.0/0 for Port 22 if it is not already set as 0.0.0.0/0
  • Now you should be able to connect.
You will see Terminal console with following message:

Using username "ec2-user".
Authenticating with public key "imported-openssh-key"
       __|  __|_  )
       _|  (     /   Amazon Linux AMI
      ___|\___|___|
https://aws.amazon.com/amazon-linux-ami/2017.03-release-notes/
1 package(s) needed for security, out of 3 available
Run "sudo yum update" to apply all updates.
[machine-info/] $


Note:
By default, JDK version .7 is installed on VM. You can change it to JDK version 8

Friday, August 14, 2015

Error on JBoss 6.2 while calling webservice when wsdl:binding tag is before wsdl:portType in WSDL

Exception while calling webservice call Jboss server when wsdl:binding tag is before wsdl:portType tag  in wsdl. 

Stack trace for error :
13:29:59,406 INFO  [stdout] (http-localhost/127.0.0.1:8080-1) Caused by: java.lang.NullPointerException
13:29:59,406 INFO  [stdout] (http-localhost/127.0.0.1:8080-1) at com.ibm.wsdl.xml.WSDLReaderImpl.parseExtensibilityAttributes(WSDLReaderImpl.java:1334)
13:29:59,407 INFO  [stdout] (http-localhost/127.0.0.1:8080-1) at com.ibm.wsdl.xml.WSDLReaderImpl.parseOperation(WSDLReaderImpl.java:1684)
13:29:59,407 INFO  [stdout] (http-localhost/127.0.0.1:8080-1) at com.ibm.wsdl.xml.WSDLReaderImpl.parsePortType(WSDLReaderImpl.java:1474)
13:29:59,407 INFO  [stdout] (http-localhost/127.0.0.1:8080-1) at com.ibm.wsdl.xml.WSDLReaderImpl.parseDefinitions(WSDLReaderImpl.java:313)
13:29:59,407 INFO  [stdout] (http-localhost/127.0.0.1:8080-1) at com.ibm.wsdl.xml.WSDLReaderImpl.readWSDL(WSDLReaderImpl.java:2265)
13:29:59,407 INFO  [stdout] (http-localhost/127.0.0.1:8080-1) at com.ibm.wsdl.xml.WSDLReaderImpl.readWSDL(WSDLReaderImpl.java:2251)
13:29:59,407 INFO  [stdout] (http-localhost/127.0.0.1:8080-1) at org.apache.cxf.wsdl11.WSDLManagerImpl.loadDefinition(WSDLManagerImpl.java:261)
13:29:59,407 INFO  [stdout] (http-localhost/127.0.0.1:8080-1) at org.apache.cxf.wsdl11.WSDLManagerImpl.getDefinition(WSDLManagerImpl.java:206)
13:29:59,407 INFO  [stdout] (http-localhost/127.0.0.1:8080-1) at org.apache.cxf.wsdl11.WSDLServiceFactory.(WSDLServiceFactory.java:98)
13:29:59,408 INFO  [stdout] (http-localhost/127.0.0.1:8080-1) at org.apache.cxf.jaxws.ServiceImpl.initializePorts(ServiceImpl.java:204)
13:29:59,408 INFO  [stdout] (http-localhost/127.0.0.1:8080-1) at org.apache.cxf.jaxws.ServiceImpl.(ServiceImpl.java:149)
13:29:59,408 INFO  [stdout] (http-localhost/127.0.0.1:8080-1) at org.jboss.wsf.stack.cxf.client.ProviderImpl$JBossWSServiceImpl.(ProviderImpl.java:509)
13:29:59,408 INFO  [stdout] (http-localhost/127.0.0.1:8080-1) at org.jboss.wsf.stack.cxf.client.ProviderImpl.createServiceDelegate(ProviderImpl.java:204)
13:29:59,408 INFO  [stdout] (http-localhost/127.0.0.1:8080-1) at javax.xml.ws.Service.(Service.java:57)

Reason:
JBoss uses wsdl4j-1.6.2.redhat-6.jar (Jboss version 6.2), which does not contain fix for the issue.
Path to jar in JBoss : \jboss-eap-6.2\modules\system\layers\base\javax\wsdl4j\api\main

[A NPE occurs when parsing a WSDL with the defined before the element. See stack trace below. The cause is in parseOperation - the line that sets 'op' to null if retrieved = true should be moved after the invocation of parseExtensibilityAttributes]

Detailed information is available at:  http://sourceforge.net/p/wsdl4j/bugs/37/


Sunday, January 4, 2015

Spring Notes : What is Spring Framework

What is Spring Framework?
Spring is a lightweight  framework for building Enterprise applications using Java. It provides all infrastructure support for developing applications. You can build your applications using POJO (Plain old java objects) without worrying about enterprise service code like transaction management, logging etc. It is a modular framework which helps you to use only those modules which are required for your application. You can easily integrate Spring features with other frameworks like Hibernate, Struts etc. Dependency Injection is main feature of Spring.

Dependency Injection:
Dependency Injection is core of Spring framework. In Dependency Injection, Container is responsible for Object Life-cycle (object creation, resolving dependencies for object etc) and enterprise applications can be built using POJO's. It can be achieved using configuration files or annotations.

Different modules of Spring:
1. Core container: Core, Beans, Context, Spring Expression language(SpEL) modules
2. Spring AOP (Aspect oriented programming) :AOP module
3. Data Access/ Integration: JDBC, ORM, OMX, JMS, Transactions modules
4. Web: Web, Web-Servlet, Web-Socket, Web-Portlet modules
5. Test : Test module for testing Spring components usinh JUnit or TestNG frameworks.

Thursday, December 18, 2014

Expression language (EL) and jstl tags in JSP

Expression language is very useful and powerful tool available for developers. With JSTL tags and expression language, we can avoid Scriptlets in JSP to make JSP code more clear and maintainable.

Here are few examples to use EL with jstl tags to perform logical operations required in JSP:

1. Condition to check value is not null or blank:
If you want to check value of "abc"  variable is not blank and not null
<c:if test="${not empty abc}">
Your HTML/JSP code
</c:if>
To print value you can also use
${not empty abc ?abc:xyz}

2. Comparision     
<c:if test="${abc eq '1'}">
Your HTML/JSP code
</c:if>
3. Multiple condition

 You can use multiple if-else condition
<c:choose>
                                    <c:when test="${not empty abc}">
                                        Code when abc not empty
                                    </c:when>
                                    <c:when test="${not empty xyz}">
                                        Code when xyz not empty
                                    </c:when>                                   
                                    <c:otherwise>
                                        Code when both abc and xyz empty
            </c:otherwise>
</c:choose>

Tuesday, July 1, 2014

How to increase SOAP request timeout value in Websphere

How to increase SOAP request timeout value in Websphere?
Change "com.ibm.SOAP.requestTimeout" configuration setting.

Path : {WebSphere-Profile-Root-Folder}\properties
File name: soap.client.props
Parameter:
com.ibm.SOAP.requestTimeout : Default value is 180, 0 implies no timeout

So when is 180 seconds timeout not enough?
Answer:  Build automation tools like Jenkins use SOAP connectivity port to deploy applications and there might be "Connection reset" error if deployment step takes more than 180 seconds.

 Exception stack trace :
exception information: com.ibm.websphere.management.exception.ConnectorException
[wsadmin] org.apache.soap.SOAPException: [SOAPException: 
faultCode=SOAP-ENV:Client; msg=Connection reset; 
targetException=java.net.SocketException: Connection reset]

Tuesday, March 4, 2014

Java 8: Release date 18th March 2014

Finally, Java 8 is releasing in few days on 18th March. Every java developer is excited to know what new features are coming.
Lambda expressions, default and static methods in Interface are few new features.
Lambda expressions will be much talked subject after people start using it.
Reality is, industry is always 5 years behind in using latest version of java.
Lets see and explore Java 8 after 18th March.

Thursday, February 20, 2014

Java : Few basic things to know about "finally" block in Exception handling

finally block is used to as cleanup facility in case of program abruptly interrupts due to exception. e.g. Closing I/O resources, closing connection etc.

Lets find out more details about finally block and answers to few basic questions.
Question 1: Can we write try block without catch?
Answer: Yes. we can write try - finally block as shown in below code example.

Question 2 : Whether finally block is executed if exception is thrown from try block?
Answer : Yes. Code in finally block will be executed even if exception is thrown from try block.

Question 3: Exception A is thrown from try block and while executing finally block, exception B is thrown. Which exception will be thrown to calling method?
Answer : Exception B which is thrown from finally block. Exception thrown from try block is discarded

Code to verify above scenarios:


/**
* Program to show how exception in try block is discarded if there is exception in finally block
*/
public class TestException {

public static void main(String[] args) {
try {
testException();
} catch (Exception e) {
System.out.println(e);
}

}

public static void testException(){
Integer j = null;
Integer k;
String [] strArray = new String []{"aa"};
try {
System.out.println("In try");
//ArrayIndexOutOfBoundsException will be thrown from below code
String testStr = strArray[1];
}
finally{
System.out.println("in finally");
//NullPointerException will be thrown from below code as j is null.
k = j *10;
}
}

}

Output after program execution:

In try
in finally
java.lang.NullPointerException


Monday, January 13, 2014

Java: Generics and Inheritance- Important things

Generics helps to write code in easy way.
-Generics makes code robust by adding strong type check at compile time check.
- Casting is not required as you define type while creating objects.


There is very important point to note related to Generics and Inheritance concept of OOPS.

Consider following java class:


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

public class TestGenericList {

/**
* @param args
*/
public static void main(String[] args) {
List< String > strList  = new ArrayList < String >();
 strList .add("a");
 strList .add("b");
 strList .add("c");
TestGenericList t = new TestGenericList();
// Can we use below code to call printList?
// t.printList(strList );

}

public void printList(List < Object > list  ){
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Object object = (Object) iterator.next();
System.out.println(object);

}
}
}


We know that String extends Object so you assume that you can pass strList object to printList function.
WRONG
You can not pass strList to printList function as function accept list of Object.

Even though String extends Object but List does not extend List< Object >



You can refer java tutorials for more details at:
http://docs.oracle.com/javase/tutorial/java/generics/inheritance.html

Tuesday, December 31, 2013

How to download source of dependencies jars using Maven

To download source of dependencies jars in local repository while building project using Maven, you need to add "dependency:sources" goal while building your project.

Run following command for your project and it will download all sources for dependencies if it exists.
Command : mvn dependency:sources

You can find more information related to dependency plugin at Maven Dependency Plugin project.


Sunday, December 1, 2013

Java: List of books you must read

Here is list of must read books if you are java developer.
1. Head first OOAD
2. Effective java
3. Java puzzlers
4. Java concurrency in practice
5. Design patterns by GOF
6. Spring in action
Your comments are welcome if you want to add to this list.

Monday, August 26, 2013

Java: Thread program to demonstrate wait and notify

Below question was asked to one of my friend during interview:

Write program to create 2 Threads "Jack" and "Jill". You write a program which will print " Jack Jill Jack Jill"
Thread execution:  Thread1, Thread2, again Thread2, then Thread2.


I tried to write program for above problem :
T1. Java:


public class T1 implements Runnable {
private static int count = 0;
public synchronized void run() {
int threadCount = 0;
while (true) {
count++;
threadCount = count;
System.out.println(Thread.currentThread().getName());

try {

notifyAll();
while (threadCount >= count) {
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}

// If you comment below if block, Jack , jill threads will run
// forever one after another.
// So added to check if Jack and Jill threads run one after another
// 2 times
if (count >= 4) {
count++;
System.out.println(Thread.currentThread().getName() + " End");
notifyAll();
break;
}
}

}
public static void main(String[] args) {
T1 t = new T1();
Thread t1 = new Thread(t, "Jack");
Thread t2 = new Thread(t , "Jill");
t1.start();
t2.start();
}

}


Output:

Jack
Jill
Jack
Jill
Jack End
Jill End

Saturday, July 27, 2013

Java : How HashMap stores and returns element

Hashing technique is useful in searching exact data in very short time.
In Java Collection Framework, Hashmap class provides functionality to store data using hashing techniques.
Here is how HashMap works internally.

Following main parameters are used to store data in HashMap:
  • Internal static class Entry which contains following variables
    • Key
    • Value
    • Next element
    • Hash value
  • Array of Entry objects (Bucket)
  • Threshold (Initial capacity * load factor)


While putting element in HashMap:
·         If key is null, it allows putting single value against null key. If you are trying to add another value against null key, it returns existing value in HashMap against null key and stores new value against null key.
o   Entry Object is stored at Bucket location 0. Hash value is also zero for null key.


·         How Value is stored against key in HashMap:
  •       Internal hash function is used to calculate hash value for hashcode of key. Hashcode of key is passed to hash function to get hash value.
  • Bucket index is found based on hash value and length of bucket. (Bucket is array which is used to store data. Data is Entry objects which contains key, value, next object and hash values). Bucket index = hash value & (bucket size-1). Bitwise and operator is used to find out index value.
  • Iterator is used to iterate over Entry objects at given index (if exists) to check if same key is already exists by comparing hash value and object equality using equals function. If same key is found, new value is stored against key and old value is returned.

Tuesday, July 16, 2013

JMS overview and sample standalone example

JMS API is used to allow applications to create, send, receive messages. It is mostly used in enterprise distributed systems (J2EE applications) for processing data asynchronously. It consists of
JMS API architecture
Messaging domain
Messaging receiver

JMS API Architecture:
JMS application consists of :

  1. JMS provider:  Messaging system that implements JMS interfaces and provide admin and control features
  2. JMS Client: Programs that produce and consume messages.
  3. Messages: objects that are transferred between JMS clients to communicate information.
  4. Administered Objects: pre configured JMS objects created by JMS administrator to be used by clients. Two kind of objects are destinations and connection factories.


There are 2 types of approaches for messaging- Point to point and Publish/subscribe.

  • Point to Point messaging: Based on message queue, message sender and message receiver. Message is addressed to specific queue. Queues retain all message until it is consumed by receiver or until message expires.
  • Publish/Subscribe messaging: In Pub/Sub messaging, message producer sends message to Topic. Message is delivered to receivers who have subscribed to that topic.

Apache ActiveMQ, Weblogic, OpenJMS, IBM Websphere MQ  are few examples of JMS provider implementations.
Below sample example shows simple standalone example of  JMS point to point messaging where administered objects (server configuration) are not used. You need Apache ActiveMQ jars to run this program.

Sample TestJMS.java file:

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.command.ActiveMQQueue;


public class TestJMS {

public static void main(String[] args) {

try {
//Start JMS service
BrokerService broker = new BrokerService();
broker.addConnector("tcp://localhost:61616");
broker.start();


ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");

Connection conn = connectionFactory.createConnection();

Queue queue = new ActiveMQQueue("testQueue");

Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

//Message Producer
MessageProducer prod = session.createProducer(queue);
//Message consumer
MessageConsumer consumer = session.createConsumer(queue);

TextMessage msg = session.createTextMessage("Hello JMS");
conn.start();
prod.send(msg);

Message message = null;
while((message = consumer.receiveNoWait()) != null){
if(message != null){
System.out.println("Message received:"+((TextMessage)message).getText());
}
}

conn.close();
broker.stop();

} catch (Exception e) {
e.printStackTrace();
}

}
}


Output of program:
Message received:Hello JMS

You can download ActiveMQ at : http://activemq.apache.org/

I have used "activemq-all-5.6.0.jar" as Build path library to run above application.

Thursday, July 4, 2013

Java: Thread Basics and Questions

Here are few general questions and answers related to Threads in Java

1. What is thread?
--> Thread is lightweight process which has its own stack trace but share resources.

2. Types of Thread:
--> Daemon thread and User thread : JVM exits when all user threads complete. It does not care whether daemon threads are complete or not.

3. How can we create Thread in java
--> a)  By extending Thread class
      b) By Implementing Runnable interface
Implementing Runnable is preferred because extending a Thread is meant to create specialized version of Class Thread where we may need some special behaviour. And We always instantiate thread by creating new instance of Thread class.

4. How to start a new thread?
--> by calling start() method of thread instance.

5. Explain different Thread states:
--> New : When thread instance is created and start method is not yet invoked. Thread t = new Thread(Runnable r);
Runnable: When thread is eligible to run but execution is not started. Threads enters in runnable state for first time when start() method is called. Thread also enters in runnable state after coming back from blocked, waiting, sleeping state.
Running: When scheduler picks thread for execution from runnable pool.
Waiting/Sleeping/Blocking: When thread is still alive but not eligible to run. Thread is not runnable but it might come to runnable when particular event happens.
Dead: Thread is dead when its run method completes. Once thread is dead, it cannot be invoke again by calling start(). It will generate runtime exception. Thread object is still valid object but not valid for separate thread of execution.

6. What is yield() method of Thread:
--> yield() method make currently running thread back to runnable pool to get other threads in runnable pool to get chance. But it is not guaranteed. Same thread can be picked up for execution by thread scheduler. When yield() is called. Thread goes from Running to Runnable state.

7. What is join() method:
--> Let one thread to join at the end of another thread. when t.join() is called. Currently running thread to join at the end of t. It means that currently running thread is blocked till t thread is complete.

8. When Currently running thread leaves running state:
a. When thread is complete. (run method is complete)
b. Thread can not acquire lock on object whose method it is trying to call.
c. When scheduler decides to move thread from running to runnable state.
d. Call to wait() on object

9. How can you prevent more than one threads to access code in Java
--> Using synchronization. We can use either synchronized method or synchronized block so that only one thread can access that method/block of code at a time.

10. How synchronization works
--> Synchronization work with lock on object. Every object in java has built in lock. When non-static method is synchronized, Thread which is running the code acquires lock on object which is calling method. No other thread can call synchronized method for that object unless current thread comes out of sync. method.
When synchronized method completes, thread releases lock so that other threads can call synchronized method on that object. Same applies for Synchronized block.
We declare synchronized block with synchronized(object){ }. We can pass any object as parameter to synchronized block. Thread acquires lock on that object. If we pass "this" as parameter to synchronized block, current instance of that class is locked.
Static methods can be synchronized. There is class instance (only one instance) of every class on which thread acquires lock.

Note: wait() method gives up lock while sleep(), yield(),join(), notify() keeps lock.

11. How thread interact with each other.
--> Using wait(), notify(), notifyAll(). Note that these methods should be called from synchronized block/method.

Wednesday, July 3, 2013

Object Oriented Programming Basic Concepts

Object oriented programming is useful for many aspects:
1. Code reuse.
2. Better design


Encapsulation: Hiding data and behaviour of an Object and provide interface (public methods) to outside objects to access data. It helps in preventing users from setting objects state directly which can cause inconsistency.

Inheritance: Way to establish relationship between objects. Here class inherit properties and method of parent class. Inheritance is termed as "Is a relationship" (Parent-Child relationship)

Polymorphism: Means many forms. Similar type of objects can behave differently for same message.
It is tightly coupled with Inheritance. Parent class provide interface(method) which is implemented differently by different child classes.


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.