Tuesday, December 4, 2012

hashcode() and equals() method

The methods hashCode() and equals() play a distinct role in the objects you insert into Java collections. The specific contract rules of these two methods are best described in the JavaDoc. Here I will just tell you what role they play. What they are used for, so you know why their implementations are important.

equals()

equals() is used in most collections to determine if a collection contains a given element. For instance:
List list = new ArrayList();
list.add("123");

boolean contains123 = list.contains("123");
The ArrayList iterates all its elements and execute "123".equals(element) to determine if the element is equal to the parameter object "123". It is the String.equals() implementation that determines if two strings are equal.
The equals() method is also used when removing elements. For instance:
List list = new ArrayList();
list.add("123");

boolean removed = list.remove("123");
The ArrayList again iterates all its elements and execute "123".equals(element) to determine if the element is equal to the parameter object "123". The first element it finds that is equal to the given parameter "123" is removed.
As you can see, a proper implementation of .equals() is essential for your own classes to work well with the Java Collection classes. So how do you implement equals() "properly"?
So, when are two objects equal? That depends on your application, the classes, and what you are trying to do. For instance, let's say you are loading and processing Employee objects stored in a database. Here is a simple example of such an Employee class:
public class Employee {
    protected long   employeeId;
    protected String firstName;
    protected String lastName;
}
You could decide that two Employee objects are equal to each other if just their employeeId's are equal. Or, you could decide that all fields must be equal - both employeeId, firstName and lastName. Here are two example implementation of equals() matching these criterias:
public class Employee {
  ...
  public boolean equals(Object o){
    if(o == null)                return false;
    if(!(o instanceof) Employee) return false;

    Employee other = (Employee) o;
    return this.employeeId == other.employeeId;
  }
}
public class Employee {
  ...
  public boolean equals(Object o){
    if(o == null)                return false;
    if(!(o instanceof) Employee) return false;

    Employee other = (Employee) o;
    if(this.employeeId != other.employeeId)      return false;
    if(! this.firstName.equals(other.firstName)) return false;
    if(! this.lastName.equals(other.lastName))   return false;

    return true;
  }
}
Which of these two implementations is "proper" depends on what you need to do. Sometimes you need to lookup an Employee object from a cache. In that case perhaps all you need is for the employeeId to be equal. In other cases you may need more than that - for instance to determine if a copy of an Employee object has changed from the original.

hashCode()

The hashCode() method of objects is used when you insert them into a HashTable, HashMap or HashSet. If you do not know the theory of how a hashtable works internally, you can read about hastables on Wikipedia.org.
When inserting an object into a hastable you use a key. The hash code of this key is calculated, and used to determine where to store the object internally. When you need to lookup an object in a hashtable you also use a key. The hash code of this key is calculated and used to determine where to search for the object.
The hash code only points to a certain "area" (or list, bucket etc) internally. Since different key objects could potentially have the same hash code, the hash code itself is no guarantee that the right key is found. The hashtable then iterates this area (all keys with the same hash code) and uses the key's equals() method to find the right key. Once the right key is found, the object stored for that key is returned.
So, as you can see, a combination of the hashCode() and equals() methods are used when storing and when looking up objects in a hashtable.
Here are two rules that are good to know about implementing the hashCode() method in your own classes, if the hashtables in the Java Collections API are to work correctly:
  1. If object1 and object2 are equal according to their equals() method, they must also have the same hash code.
  2. If object1 and object2 have the same hash code, they do NOT have to be equal too.
In shorter words:
  1. If equal, then same hash codes too.
  2. Same hash codes no guarantee of being equal.
Here are two example implementation of the hashCode() method matching the equals() methods shown earlier:
public class Employee {
  protected long   employeeId;
  protected String firstName;
  protected String lastName;

  public int hashCode(){
    return (int) this.employeeId;
  }
}
public class Employee {
    protected long   employeeId;
    protected String firstName;
    protected String lastName;

  public int hashCode(Object o){
    return (int)this.employeeId *
                firstName.hashCode() *
                lastName.hashCode();
  }
}
Notice, that if two Employee objects are equal, they will also have the same hash code. But, as is especially easy to see in the first example, two Employee objects can be not equal, and still have the same hash code.
In both examples the hash code is the employeeId is rounded down to an int. That means that many employee id's could result in the same hash code, but these Employee objects would still not be equal, since they don't have the same employee id.

More Detail in the JavaDoc

For a 100% precise description of how to implement equals() and hashCode() you should check out the official JavaDoc's. The purpose of this text was mostly to explain how they are used by the Java Collection classes. Understanding this makes it easier to implement them to suit your purposes.

Sorting in Collections

You can sort List collections using the java.util.Collections.sort() method. You can sort these two types of List's.
  1. List
  2. LinkedList

Sorting Objects by their Natural Order

To sort a List you do this:
List list = new ArrayList();

//add elements to the list

Collections.sort(list);
When sorting a list like this the elements are ordered according to their "natural order". For objects to have a natural order they must implement the interface java.lang.Comparable. In other words, the objects must be comparable to determine their order. Here is how the Comparable interface looks:
public interface Comparable<T> {
  int compareTo(T o);
}
The compareTo() method should compare this object to another object, return an int value. Here are the rules for that int value:
  • Return a negative value if this object is smaller than the other object
  • Return 0 (zero) if this object is equal to the other object.
  • Return a positive value if this object is larger than the other object.
There are a few more specific rules to obey in the implementation, but the above is the primary requirements. Check out the JavaDoc for the details.
Let's say you are sorting a List of String elements. To sort them, each string is compared to the others according to some sorting algorithm (not interesting here). Each string compares itself to another string by alphabetic comparison. So, if a string is less than another string by alphabetic comparison it will return a negative number from the compareTo() method.
When you implement the compareTo() method in your own classes you will have to decide how these objects should be compared to each other. For instance, Employee objects can be compared by their first name, last name, salary, start year or whatever else you think makes sense.

Sorting Objects Using a Comparator

Sometimes you may want to sort a list according to another order than their natural order. Perhaps the objects you are sorting do not even have a natural order. In that case you can use a Comparator instead. Here is how you sort a list using a Comparator:
List list = new ArrayList();

//add elements to the list

Comparator comparator = new SomeComparator();

Collections.sort(list, comparator);
Notice how the Collections.sort() method now takes a java.util.Comparator as parameter in addition to the List. This Comparator compares the elements in the list two by two. Here is how the Comparator interface looks:
public interface Comparator<T> {
    int compare(T object1, T object2);
}
The compare() method compares two objects to each other and should:
  • Return a negative value if object1 is smaller than object2
  • Return 0 (zero) if objec1 is equal to object2.
  • Return a positive value if object1 is larger than object2.
There are a few more requirements to the implementation of the compare() method, but these are the primary requirements. Check out the JavaDoc for more specific details.
Here is an example Comparator that compares two fictive Employee objects:
public class MyComparator<Employee> implements Comparator<Employee> {

    public int compare(Employee emp1, Employee emp2){
       if(emp1.getSalary() <  emp2.getSalary()) return -1;
       if(emp1.getSalary() == emp2.getSalary()) return 0;
       return 1;
    }
}
A shorter way to write the comparison would be like this:
public class MyComparator<Employee> implements Comparator<Employee> {

    public int compare(Employee emp1, Employee emp2){
       return emp1.getSalary() - emp2.getSalary();
    }
}
By subtracting one salary from the other, the resulting value is automatically either negative, 0 or positive. Smart, right?
If you want to compare objects by more than one factor, start by comparing by the first factor (e.g first name). Then, if the first factors are equal, compare by the second factor (e.g. last name, or salary) etc

Sunday, November 25, 2012

Short Job First(sjf) based on arrival time(non-preemptive)

/* Simulate the following cpu scheduling algorithms.             '
    B. Short Job First(sjf) based on arrival time(non-preemptive).   */

#include<stdio.h>
#include<conio.h>
void swap(int *x,int *y)
{
    int *temp;
    *temp=*x;
    *x=*y;
    *y=*temp;
}
void main()
{
    int i,j,bt[10],bt1[10],n,twt=0,temp1,z[20],p[10];
    int wt[10],sum=0,sum1=0,at[10],k,l;
    float avgt=0.00;
    clrscr();
    printf("\n Enter no. of Processes ::");
    scanf("%d",&n);
    printf("\n Enter the %d burst times::",n);
    for(i=0;i<n;i++)
    {
        printf("\n\n Enter burst and arrival times for process%d::",i+1);
        scanf("%d%d",&bt[i],&at[i]);
        p[i]=i+1;
    }
    i=j=0;
    while(at[j+1]<bt[i])
        j++;

    for(k=0;k<j;k++)
        bt1[k]=bt[k+1];
    /*for(i=0;i<j;i++)
        printf("%6d",bt1[i]);*/
    for(i=1;i<j-1;i++)
    {
        for(k=i+1;k<j;k++)
        {
            if(bt[i]>bt[k])
                swap(&bt[i],&bt[k]);
        }
    }
/*    for(i=0;i<j;i++)
        printf("\n%4d",bt1[i]); */
    for(i=0;i<n;i++)
    {
        if(i==0)
        {
            wt[i]=0;
            sum=sum+bt[i];
            sum1=sum1+bt[i];
        }
        else
        {
            sum=sum+bt[i];
            wt[i]=sum-at[i];

        }
        sum1=sum1+bt[i];
        z[i]=sum1;

    }
    /*for(i=0;i<n;i++)
        printf("%d",p[i]);   */
    printf("\n\n----------------------------------------------\n");
    printf("\n\tPNo\tbt\tat\twt\n");
    printf("\n----------------------------------------------\n");
    for(i=0;i<n;i++)
    {
        twt+=wt[i];
        printf("\n\n\tP%d\t%d\t%d\t%d\n",p[i],bt[i],at[i],wt[i]);
    }
    printf("\n----------------------------------------------\n");
    avgt=(float)twt/(float)n;
    printf("\n\nGannt Chart ::\n\n");
    printf("\t0");
    for(i=1;i<n;i++)
        printf("%4d",z[i]);
    printf("\n\n Total waiting time is ::%d",twt);
    printf("\n\n Average waiting time is ::%f",avgt);
    getch();
}

/* Input and Output :-


 Enter no. of Processes ::3
 Enter the 3 burst times::
 Enter time for process1::24
 Enter time for process2::3
 Enter time for process3::3
  231
----------------------------------------------
    PNo     bt      wt
----------------------------------------------
    P2      3       0
    P3      3       3
    P1      24      6
----------------------------------------------

Gannt Chart ::

    0   3   6

 Total waiting time is ::9
 Average waiting time is ::3.000000        */


ListIterator program in Collection

import java.util.*;
class TestListIterator
{
    public static void main(String[] args)
    {
        ArrayList<Integer> al=new ArrayList<Integer>();
        al.add(10);
        al.add(20);
        al.add(30);
        al.add(40);
        ListIterator it=al.listIterator();
        while(it.hasNext())
        {
            System.out.println(it.next());
        }
        while(it.hasPrevious())
        {
            System.out.println(it.previous());
        }
    }
}

HashSet Example program in Collections

import java.util.*;
class TestHashSet
{
    public static void main(String[] args)
    {
        HashSet<String> hs=new HashSet<String>();
        hs.add("Ram");

        hs.clear();
        hs.add("sree");
        hs.add("sri");
        hs.add("Rama");
        hs.remove("Ram");
        //System.out.println(hs.contains("sita"));
    System.out.println(hs.isEmpty());
        System.out.println(hs.size());
                System.out.println
(hs);
    }
}

Demo on ForEach loop in collections

import java.util.*;
class TestForEach
{
    public static void main(String[] args)
    {
        ArrayList<Integer> al=new ArrayList<Integer>();
        al.add(10);
        al.add(20);
        al.add(30);
        al.add(40);
        Iterator it=new Iterator();
        while(it.hasNext())
        {
            System.out.println(it.next());
        }
    }
}   

Saturday, November 24, 2012

Demo Program on Enumeration


import java.util.*;
class TestEnumeration
{
public static void main(String[] args)
{
ArrayList<Integer> al=new ArrayList<Integer>();
al.add(10);
al.add(20);
al.add(30);
al.add(40);
Enumeration e=Collections.enumeration(al);
while(e.hasMoreElements())
{
System.out.println(e.nextElement());
}
/*while(it.hasPrevious())
{
System.out.println(it.previous());
}*/
}
}

/*

boolean hasMoreElements()
element nextElement():

*/

Friday, September 7, 2012

Difference Between NoClassDefinitionFound and ClassNotFound Exception


What is Exception in thread "main" java.lang.NoClassDefFoundError?
I know how frustrating is to see Exception in thread "main" java.lang.NoClassDefFoundError  Which is a manifestation of NoClassDefFoundError in Java , I have seen it couple of times and spent quite a lot time initially to figure out what is wrong , which class is missing etc. First mistake I did was mingling java.lang.ClassNotfoundException and NoClassDefFoundError, in reality they are totally different and second mistake  was using trial and error method to solve this java.lang.NoClassDefFoundError instead of understanding why NoClassDefFoundError is coming, what is real reason behind NoClassDefFoundError and how to resolve this. In this Java tutorial I have tried to rectify that mistakes and uncover some secrets of NoClassDefFoundError in Java and will share my experience around it. NoClassDefFoundError is not something which cannot be resolved or hard to resolve it’s just its manifestation which puzzles most of Java developer. This is the most common error in Java development along with java.lang.OutOfMemoroyError: Java heap space and java.lang.OutOfMemoryError: PermGen space  Anyway let’s see Why NoClassDefFoundError comes in Java and what to do to resolve NoClassDefFoundError in Java.


What is reason of NoClassDefFoundError in Java?
NoClassDefFoundError in Java comes when Java Virtual Machine is not able to find a particular class at runtime which was available during compile time. For example if we have a method call from a class or accessing any static member of a Class and that class is not available during run-time then JVM will throw NoClassDefFoundError. It’s important to understand that this is different than ClassNotFoundException which comes while trying to load a class at run-time only and name was provided during runtime not on compile time. Many Java developer mingle this two Error and gets confused.

In short NoClassDefFoundError will come if a class was present during compile time but not available in java classpath during runtime. Normally you will see below line in log when you get NoClassDefFoundError:

Exception in thread "main" java.lang.NoClassDefFoundError

Exception in thread “main” simply indicate that its “main” thread which is not able to find a particular class it could be any thread so just don’t worry . Difference between this error coming in main thread and other thread is , when Exception in thread “main” comes program crashes or shut it self down as opposed to other thread in which case your program will continue to run.,

Difference between java.lang.NoClassDefFoundError and ClassNotFoundException in Java

Many a times we confused ourselves with java.lang.ClassNotFoundException and java.lang.NoClassDefFoundError, though both of them related to Java Classpath they are completely different to each other. ClassNotFoundException comes when JVM tries to load a class at runtime dynamically means you give the name of class at runtime and then JVM tries to load it and if that class is not found in classpath it throwsjava.lang.ClassNotFoundException. While in case of NoClassDefFoundError the problematic class was present during Compile time and that's why program was successfully compile but not available during runtime by any reason. NoClassDefFoundError is easier to solve than ClassNotFoundException in my opinion because here we know that Class was present during build time but it totally depends upon environment, if you are working in J2EE environment than you can get NoClassDefFoundError even if class is present because it may not be visible to corresponding ClassLoader. See my post NoClassDefFoundError vs ClassNotFoundException in Java for more details.

How to resolve java.lang.NoClassDefFoundError:

java.lang.NoClassDefFoundError in Java solution Obvious reason of NoClassDefFoundError is that a particular class is not available in Classpath, so we need to add that into Classpath or we need to check why it’s not available in Classpath if we are expecting it to be. There could be multiple reasons like:

1) Class is not available in Java Classpath.
2) You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
3) Any start-up script is overriding Classpath environment variable.
4) Because NoClassDefFoundError is a sub class of java.lang.LinkageError it can also come if one of it dependency like native library may not available.
4) Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to failure of static initialization is quite common.
5) If you are working in J2EE environment than visibility of Class among multiple Classloaders can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.

We will now see couple of example and scenarios when java.lang.NoClassDefFoundError has came before and how its been resolved. This can help you to troubleshoot root cause of NoClassDefFoundError in Java application.


NoClassDefFoundError in Java - Example and Scenarios

1. Simple example of NoClassDefFoundError is class belongs to a missing JAR file or JAR was not added into classpath or sometime jar's name has been changed by someone like in my case one of my colleague has changed tibco.jar into tibco_v3.jar and by program is failing with java.lang.NoClassDefFoundError and I was wondering what's wrong.

2. Class is not in Classpath, there is no sure shot way of knowing it but many a times you can just have a look to print System.getproperty("java.classpath")and it will print the classpath from there you can at least get an idea of your actual runtime classpath.

3. Just try to run with explicitly -classpath option with the classpath you think will work and if its working then it's sure short sign that some one is overriding java classpath.

NoClassDefFoundError in Java due to Exception in Static Initializer block
4) This is another common reason of java.lang.NoClassDefFoundError, when your class perform some static initialization in static block like many Singleton classes initialized itself on static block  to take advantage of thread-safety provided by JVM during class initialization process, and if static block throw an Exception, the class which is referring to this class will get NoclassDefFoundError in Java. If you look at your log file you should watch for any java.lang.ExceptionInInitializerError because that could trigger java.lang.NoClassDefFoundError: Could not initialize class on other places. Like in below code example, During class loading and initialization User class is throwing Exception from static initializer block, which trigger ExceptionInInitializerError during first time loading of User class in response to new User() call. Later rest of new User() are failing as java.lang.NoClassDefFoundError. situation gets worst if original ExceptionInInitializerError, which is root cause here is silently eaten by any code.

Code Example of NoClassDefFoundError due to Static block Exception:

/**
 * Java program to demonstrate how failure of static initialization subsequently cause
 * java.lang.NoClassDefFoundError in Java.
 * @author Javin Paul
 */

public class NoClassDefFoundErrorDueToStaticInitFailure {

    
public static void main(String args[]){
     
        List
<User> users = new ArrayList<User>(2);
     
        
for(int i=0; i<2; i++){
            
try{
            users.
add(new User(String.valueOf(i))); //will throw NoClassDefFoundError
            
}catch(Throwable t){
                t.
printStackTrace();
            
}
        
}      
    
}
}
class User{
    
private static String USER_ID = getUserId();
 
    
public User(String id){
        
this.USER_ID = id;
    
}
    
private static String getUserId() {
        
throw new RuntimeException("UserId Not found");
    
}     }

Output
java.lang.ExceptionInInitializerError
    at testing.NoClassDefFoundErrorDueToStaticInitFailure.main(NoClassDefFoundErrorDueToStaticInitFailure.java:23)
Caused by: java.lang.RuntimeException: UserId Not found
    at testing.User.getUserId(NoClassDefFoundErrorDueToStaticInitFailure.java:41)
    at testing.User.<clinit>(NoClassDefFoundErrorDueToStaticInitFailure.java:35)
    ... 1 more
java.lang.NoClassDefFoundError: Could not initialize class testing.User
    at testing.NoClassDefFoundErrorDueToStaticInitFailure.main(NoClassDefFoundErrorDueToStaticInitFailure.java:23)


5) Since NoClassDefFoundError is a  also a LinkageError which arises due to dependency on some other class , you can also get java.lang.NoClassDefFoundError if your program is dependent on native library and corresponding dll is not there. Remember this can also trigger java.lang.UnsatisfiedLinkError: no dll in java.library.path Exception JavaIn order to solve this keep your dll along with JAR.

6) If you are using ANT build file create JAR and manifest file than its worth noting to debug till that level to ensure that ANT build script is getting correct value of classpath and appending it to manifest.mf file.

7) Permission issue on JAR file can also cause NoClassDefFoundError in Java. If you are running your Java program in multi-user operating system like Linux than you should be using  application user id for all your application resources like JAR files, libraries and configuration. If you are using shared library which is shared among multiple application which runs under different users  then you may run with permission issue , like JAR file is owned by some other user and not accessible to your application. One of our reader “it’s me said” faced java.lang.NoClassDefFoundError due to this reason. See his comment also.

8) Typo on XML Configuration can also cause NoClassDefFoundError in Java. As most of Java frameworks like SpringStruts they all use xml configuration for specifying beans. By any chance if you put the bean name wrong, it may surface as java.lang.NoClassDefFoundError while loading other class which has dependency on wrongly named bean. This is quite common on Spring MVC framework and Apache Struts where you get tons of Exception in thread "main" java.lang.NoClassDefFoundError while deploying your WAR or EAR file.

9) Another example of java.lang.NoClassDefFoundError as mentioned by our reader Nick is that when your compiled class which is defined in a package, doesn’t present in same package while loading like in case of JApplet it will throw NoClassDefFoundError in Java. Also see Nick’s comment on this error.

10) java.lang.NoClassDefFoundError can be caused due to multiple classloaders in J2EE environments. Since J2EE doesn’t mention standard class-loader structure and it depends upon different vendors like TomcatWebLogic, WebSphere on how they load different components of J2EE like WAR file or EJB-JAR file. In order to troubleshoot NoClassDefFoundError in J2EE application knowledge of How ClassLoader works in Java is mandatory. Just to recap ClasLoader works on three principle delegation, visibility and uniqueness. Delegation means every request to load a class is delegated to parent classloader, visibility means ability to found classes loaded by classloader, all child classloader can see classes loaded by parent classloader but parent classloader can not see the class loaded by child classloaders. Uniqueness enforce that class loaded by parent will never be reloaded by child clasloaders. Now suppose if a class say User is present in both WAR file and EJB-JAR file and loaded by WAR classloader which is child classloader which loads class from EJB-JAR. When a code in EJB-JAR refer to this User class, Classloader which loaded all EJB class doesn’t found that because it was loaded by WAR classloader which is child of it. This will result injava.lang.NoClassDefFoundError for User class. Also If class is present in both JAR file and you will call equals method to compare those two object, it will result in ClassCastException as object loaded by two different classloader can not be equal.

11) Some of reader of this blog also suggested that they get Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/tools/javac/Main , this error means either your ClasspathPATH  or JAVA_HOME is not setup properly or JDK installation is not correct. which can be resolved by re-installing JDK. IF you are getting this error try to reinstall JDK . One of our reader got this issue after installing jdk1.6.0_33 and then reinstalling JDK1.6.0_25, he also has his JRE and JDK on different folder. See his comment also by searching JDK1.6.0_33 .

12) Java program can also throw java.lang.NoClassDefFoundError during linking which occurs during class loading in Java. One of the example of this scenario is just delete the User class from our static initializer failure example after compilation and they try to run the program. This time you will get java.lang.NoClassDefFoundError directly without  java.lang.ExceptionInInitializerError and message for NoClassDefFoundError is also just printing name of class as testing/User i.e. User class from testing package. Watch out for this carefully as here root cause is absent of User.class file.

java.lang.NoClassDefFoundError: testing/User
    at testing.NoClassDefFoundErrorDueToStaticInitFailure.main(NoClassDefFoundErrorDueToStaticInitFailure.java:23)


Let me know how exactly you are facing NoClassDefFoundError in Java  and I will guide you how to troubleshoot it, if you are facing with something new way than I listed above we will probably document if for benefit of others and again don’t afraid with Exception in thread "main" java.lang.NoClassDefFoundError 


Read more: http://javarevisited.blogspot.com/2011/06/noclassdeffounderror-exception-in.html#ixzz25qjlR4dH

How to create read only Collection in Java


 


SUNDAY, September 8, 2012


How to create read only Collection in Java

Read only Collection in Java
You can create read only Collection by using Collections.unmodifiableCollection() utiltiy method. it returns unmodifiable or readonly view of Collection in which you can not perform any operation which will change the collection like add() , remove()and set() either directly or while iterating over iterator. It raise UnsupportedOperationException whenever you try to modify the List. One of the common misconception around read only ArrayList is that, you can create read only arrayList by usingArrays.asList(String{[]), which is apparently not true as this method only return a fixed size list on which add() andremove() are not allowed by set() method is still allowed which can change the contents of ArrayListCollections class also provide different method to make List and Set read only. In this Java tutorial we will learn How to make any collection read only and How to create fixed size List as well.

READ ONLY COLLECTION EXAMPLE - JAVA

How to make Collection Read only in Java examplehere is code example of creating and making existing ArrayList read only. This example uses Arrays.asList()method to create a fixed length ArrayList which is initialized during creation on same line and than later wrapped it into unmodifiable collection to make it read only.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * Java program to create read only Collection in Java. apparently you can make any
 * Collection read only by using Collections.unmodifiableCollection(), there are separate
 * method for List and Set as well.
 * @author
 */

public class ReadOnlyCollection {


    public static void main(String args[]) {
   
        //creating read only Collection in Java
        Collection readOnlyCollection = Collections.unmodifiableCollection(newArrayList<String>());
        readOnlyCollection.add("Sydney Sheldon"); //raises UnSupportedOperation exception
 
        //making existing ArrayList readonly in Java
        ArrayList readableList = new ArrayList();
        readableList.add("Jeffrey Archer");
        readableList.add("Khalid Hussain");
   
        List unmodifiableList = Collections.unmodifiableList(readableList);
   
        //add will throw Exception because List is readonly
        unmodifiableList.add("R.K. Narayan");
   
        //remove is not allowed in unmodifiable list
        unmodifiableList.remove(0);
   
        //set is not allowed in unmodifiable List
        unmodifiableList.set(0"Anurag Kashyap");
   
        //creating Fixed Length List from Array in Java
        List fixedLengthList = Arrays.asList("Mark" , "Twen");
        // readOnlyList.add("J.K. Rowling"); //raises Exception
   
        fixedLengthList.set(0"J.K. Rowling"); //allowed that's why not read only list
        System.out.println(fixedLengthList.get(0));
    }

}

If you un-comment lines which supposed to raise Exception than you will get Exception like this:

Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.Collections$UnmodifiableCollection.add(Collections.java:1018)
        at test.CollectionTest.main(CollectionTest.java:24)

If you comment all the lines which does modification on read only list than you can test the last line which changes the value of an element in fixed length ArrayList.

That’s all on How to create read only Collection in Java. Read only collection is also called unmodifiable collection and does not allow any modification operation like add() , remove() or set() operation. Remember read only collection is different than fixed length collection which does not allow add or remove method but allow to update value of existing element using set method.

Friday, July 27, 2012

Difference Between HashMap and HashTable



This question oftenly asked in interview to check whether candidate understand correct usage of collection classes and aware of alternative solutions available.

1. The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is  fail-fast  while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally  by adding or removing any element except Iterator's own remove()  method. But this is not a guaranteed behavior and will be done by JVM on best effort.

Note on Some Important Terms

1)Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.

2)Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception wjavascript:void(0)ill be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.

3)Structurally modification means deleting or inserting element which could effectively change the structure of map.

HashMap can be synchronized by

Map m = Collections.synchronizeMap(hashMap);

Hope this will be useful.Please provide your valuable feed back for us! Thank you for visiting here !