Search This Blog

Saturday, February 4, 2012

Navigable Map Example

We already know that NavigableMap is similar to NavigableSet. In NavigableMap we use methods to return the key value pair like navMap.put(1, "January"); whereas in NavigableSet we use methods to return values. ConcurrentSkipListMap is the one of the class which implements NavigableMap. Lets have a look at the example.

Description of program:

The following program helps you in inserting, removing and retrieving the data from the NavigableMap. It uses the put() method to add the element. If you want to retrieve the data at first and last position from the NavigableMap, you use the firstEntry() and lastEntry() methods. The descendingMap() method represents all data to the NavigableMap in descending order.

You can retrieve the nearest less than or equal to the given number and the greatest key strictly less than the given number floorEntry() and lowerEntry() methods. And you retrieve a key-value associated with the least key strictly greater than the given key, you use the higherEntry() method. The pollFirstEntry() method removes the first data from the NavigableMap and pollLastEntry() method also removes the data at the last position from the NavigableMap.

Here is the code of program:

import java.util.*;
import java.util.concurrent.*;

public class NavigableMapExample{
public static void main(String[] args) {
System.out.println("Navigable Map Example!\n");
NavigableMap navMap = new
ConcurrentSkipListMap();
navMap.put(1, "January");
navMap.put(2, "February");
navMap.put(3, "March");
navMap.put(4, "April");
navMap.put(5, "May");
navMap.put(6, "June");
navMap.put(7, "July");
navMap.put(8, "August");
navMap.put(9, "September");
navMap.put(10, "October");
navMap.put(11, "November");
navMap.put(12, "December");
//Displaying all data
System.out.println("Data in the navigable map: " +
navMap.descendingMap
()+"\n");
//Retrieving first data
System.out.print("First data: " + navMap.firstEntry()+"\n");
//Retrieving last data
System.out.print("Last data: " + navMap.lastEntry()+"\n\n");
//Retrieving the nreatest less than or equal to the given key
System.out.print("Nearest less than or equal to the given key: "
+ navMap.floorEntry(5)+"\n");
//Retrieving the greatest key strictly less than the given key
System.out.println("Retrieving the greatest key strictly less than
the given key: "
+ navMap.lowerEntry(3));
//Retrieving a key-value associated with the least key
strictly greater than the given key

System.out.println("Retriving data from navigable map greter than
the given key: "
+ navMap.higherEntry(5)+"\n");
//Removing first
System.out.println("Removing First: " + navMap.pollFirstEntry());
//Removing last
System.out.println("Removing Last: " + navMap.pollLastEntry()+"\n");
//Displaying all data
System.out.println("Now data: " + navMap.descendingMap());
}
}

Download this example.

Output of program:

C:\vinod\collection>javac NavigableMapExample.java

C:\vinod\collection>java NavigableMapExample
Navigable Map Example!

Data in the navigable map: {12=December, 11=November, 10=October, 9=September, 8
=August, 7=July, 6=June, 5=May, 4=April, 3=March, 2=February, 1=January}

First data: 1=January
Last data: 12=December

Nearest less than or equal to the given key: 5=May
Retrieving the greatest key strictly less than the given key: 2=February
Retriving data from navigable map greter than the given key: 6=June

Removing First: 1=January
Removing Last: 12=December

Now data: {11=November, 10=October, 9=September, 8=August, 7=July, 6=June, 5=May
, 4=April, 3=March, 2=February}

C:\vinod\collection>

Collections Framework Enhancements

In Collection framework, we are able to improve the performance hashing function that is used by java.util.HashMap. It provides some new Collection interfaces also.

Following new Interfaces and Classes are provided in JAVA SE 6 :

  • Deque ? Deque is a interface. It is a short for ?Double Ended Queue?. This interface defines some methods that access the element at both ends. That means by the methods of this interface we can add and remove the elements at both ends.
  • ArrayDeque ? ArrayDeque Class implements a Deque interface. This class have no capacity restriction, it can grow according to usage. If the external Synchronization is not available then it don?t support concurrent access by multiple thread.

Constructors Details :

  • public ArrayDeque()
    Above Constructor is used to make a empty array deque with an default capacity that 16 elements.
  • public ArrayDeque(int numElements)
    Above Construtor is used to make a empty array deque with the initial capacity that is sufficient to hold the specified elements.
  • public ArrayDeque()
    Etype is the type of the elements that held in this Collection. Above Constructor is used to make a array deque containing elements of specified type.

Methods Details :

  • void addFirst(Etype e)
    Above method is used to insert the element at the starting point of the array deque
  • void addLast(Etype e)
    Above method is used to insert the element at the end point of the array deque.

Above two methods throws following Exception:

  1. IllegalStateException ? Due to capacity restriction the element cannot be added.
  2. ClassCastException ? Class of the specified element prevents it from being added to this deque
  3. NullPointerException ? If specified element is null.
  4. IllegalArgumentException ? If element having some property that prevent it from being added to this deque
  • boolean offerFirst(Etype e)
    Above method is also used to insert the specified element at the starting point of the array deque. This method is preferable when we using a capacity restricted deque. When element is added in array deque then its return true else it return false.
  • boolean offerLast(Etype e)
    Above method is also used to insert the specified element at the end point of the array deque. This method is preferable when we using a capacity restricted deque. When element is added in array deque then its return true else it return false.

Above two methods throws following Exception:

  1. ClassCastException ? Class of the specified element prevents it from being added to this deque.
  2. NullPointerException ? If specified element is null.
  3. IllegalArgumentException ? If element having some property that prevent it from being added to this deque.
  • Etype removeFirst()
    Above method is used to remove the first element of the array deque. And we can also retrieve this element. But if array deque is empty then it throws a NoSuchElementException.
  • Etype removeLast()
    Above method is used to remove the last element of the array deque. And we can also retrieve this element. But if array deque is empty then it throws a NoSuchElementException.
  • Etype pollFirst()
    Above method is same as removeFirst(). It is also used to retrieve and remove the first element of the deque. But it does not throws any Exception even the deque is empty, its only return null.

  • Etype pollLast()
    Above method is same as removeLast(). It is also used to retrieve and remove the last element of the deque. But it does not throws any Exception even the deque is empty, its only return null.
  • Etype getFirst()
    Above method is used just for retrieving the first element of deque. But if array deque is empty then it throws a NoSuchElementException.
  • Etype getLast()
    Above method is used just for retrieving the last element of deque. But if array deque is empty then it throws a NoSuchElementException.
  • Etype peekFirst()
    Above method is same as getFirst().It is also used to retrieving the first element of the deque. But it does not throws any Exception even the deque is empty, its only return null.
  • Etype peekLast()
    Above method is same as getLast().It is also used to retrieving the last element of the deque. But it does not throws any Exception even the deque is empty, its only return null.
  • boolean removeFirstOccurrence(Object obj)
    Above method is used to remove the first occurrence of the specified element. It return true when the specified element was remove. But if the deque does not contain the specified element it is unchanged.
  • boolean removeLastOccurrence(Object obj)
    Above method is used to remove the last occurrence of the specified element. It return true when the specified element was remove. But if the deque does not contain the specified element it is unchanged.
The following example demonstrates the above methods:
import java.io.*; import java.util.*;
public class NewDeque {
 public static void main(String s[])throws IOException  {
  Console c=System.console();   if(c==null)     {   System.err.println("Console object is not available");    System.exit(1);   }   ArrayDeque dqname = new ArrayDeque();    String name = null;
   name = c.readLine("Enter any String: ");    dqname.add(name);        show(dqname);     name=c.readLine("Enter any string to add on starting  point of deque by addFirst():");    dqname.addFirst(name);    show(dqname);
   name=c.readLine("Enter any string to add on ending  point of deque by addLast():");    dqname.addLast(name);    show(dqname);
  name=c.readLine("Enter any string to add on starting  point of deque by offerfirst() :");    dqname.offerFirst(name);    show(dqname);
   name=c.readLine("Enter any string to add on ending  point of deque by offerlast() :");    dqname.offerLast(name);    show(dqname);
   System.out.println("Getting the first element  by using getFirst()");    String str1=dqname.getFirst();    System.out.println("First element is  : "+str1);
  System.out.println("Getting the Last element by using  getLast()");    str1=dqname.getLast();    System.out.println("Last element is  : "+str1);  
   System.out.println("Getting the first element by  using peekFirst()");    str1=dqname.peekFirst();    System.out.println("First element is  : "+str1);  
   System.out.println("Getting the Last element by  using peekLast()");    str1=dqname.peekLast();    System.out.println("Last element is  : "+str1);
   System.out.println("Removing the first element  by using removeFirst()");    str1=dqname.removeFirst();    show(dqname);   
   System.out.println("Removing the Last element  by using removeLast()");    str1=dqname.removeLast();
   show(dqname);
   System.out.println("Removing the first element  by using pollFirst()");    str1=dqname.pollFirst();    show(dqname);
   System.out.println("Removing the Last element  by using pollFirst()");    str1=dqname.pollLast();    show(dqname);  }
   static void show(ArrayDeque dqname)    {    Iterator nameIter = dqname.iterator();     while(nameIter.hasNext())
   System.out.println(nameIter.next());     } }

Output of the program is:

C:\j2se6>javac NewDeque.java

C:\j2se6>java NewDeque
Enter any String: Rose
Rose
Enter any string to add on starting point of deque by addFirst():India
India
Rose
Enter any string to add on ending point of deque by addLast():Net
India
Rose
Net
Enter any string to add on starting point of deque by offerfirst() :Com
Com
India
Rose
Net
Enter any string to add on ending point of deque by offerlast() :Chandan
Com
India
Rose
Net
Chandan
Getting the first element by using getFirst()
First element is : Com
Getting the Last element by using getLast()
Last element is : Chandan
Getting the first element by using peekFirst()
First element is : Com
Getting the Last element by using peekLast()
Last element is : Chandan
Removing the first element by using removeFirst()
India
Rose
Net
Chandan
Removing the Last element by using removeLast()
India
Rose
Net
Removing the first element by using pollFirst()
Rose
Net
Removing the Last element by using pollFirst()
Rose

C:\j2se6>

Custom Collection Implementations

So far you have learnt about the Java built-in Collection Interfaces implementations. Apart from these, some times programmer need to implement their own collections classes. The Java platform allows you to write your own implementation of a core collection interface. It is easy to write your own implementation with the help of abstract implementations.

Lets discuss, why we should make a custom implementation.

  • Persistent: All of the built-in Collection implementations reside in main memory and appears when the program exits. If you want a collection to be available for the next time when the program starts, you can implement a collection that is concurrently accessible by multiple programs.
  • High-performance, special-purpose: Many data structures take advantage of restricted usage to offer better performance that is possible with general-purpose implementations. For instance, consider a List containing long runs of identical element values. The runs can be represented as a single object containing the repeated element. This example is interesting because it deals with two aspects of performance: It requires less space but more time than an ArrayList.
  • High-performance, general-purpose: The Java Collections Framework's designers have tried to provide the best general-purpose implementations for each interface, but many, new ones are invented every day for the High performance of an application.
  • Convenience: Some times you want additional implementations that offers conveniences than those offered by the Java platform. For instance, you may need a List to represent a contiguous range of Integers.

To write your own custom implementation is not difficult. Java supports the abstract implementations to implement your own collection. Lets see the way of writing the custom collection implementation.

import java.util.*;

class MyClass {
public static List myList(Object[] a) {
return new ArrayList(a);
}
}
class ArrayList extends AbstractList
implements java.io.Serializable {

private Object[] x;

ArrayList(Object[] array) {
x
= array;
}
public Object get(int index) {
return x[index];
}
public Object set(int index, Object element) {
Object oldVal = x[index];
x
[index] = element;
return oldVal;
}
public int size() {
return x.length;
}
}
public class CustomImpl{
public static void main(String[] args) {
try{
String s[]={"My", "Custom", "Implementation"};
Object o;
int i=0;
MyClass a= new MyClass();
List lst=a.myList(s);
System.out.println("The list is: "+lst);
ArrayList al=new ArrayList(s);
o
=al.get(1);
System.out.println("The retrieved element is: "+o);
String s1="Collection";
o
=al.set(2,s1);
System.out.println("The set element in place of Implementation is: "+s1);
System.out.println("Now the new list is: "+lst);
i
=al.size();
System.out.println("The size of the array list is: "+i);
}
catch(Exception e){}
}
}


Output of the Program:

C:\nisha>javac CustomImpl.java

C:\nisha>java CustomImpl
The list is: [My, Custom, Implementation]
The retrieved element is: Custom
The set element in place of Implementation is: Collection
Now the new list is: [My, Custom, Collection]
The size of the array list is: 3

C:\nisha>

Description of the Program:

In the given program, a custom implementation of Arrays.myList is defined which calls the constructor of ArrayList class and pass the object to it. The get( ) and the set( ) methods of the ArrayList class retrieve and set an element to the specified position of the List.

Searching Algorithm :

Besides sorting, the Collections and Arrays classes provide a mechanism to search a List or an array, as well as to find the first and last values within a Collection. The binarySearch algorithm searches for a specified element in a sorted List. This algorithm takes a List and an element to search for the search key. This form assumes that the List is sorted in ascending order according to the natural ordering of its elements.

Before searching an element, the List must be sorted, Once you have sorted the List, using Collection.sort( ) method, you can perform a quickly binary search operation using the overridden binarySearch( ) method.

For example, the following program prints the sorted arguments list (the arguments, given through command line) and then search the position of a specified key value.

import java.util.*;

public class SearchDemo {
public static void main(String[] args) {
try{
List list = Arrays.asList(args);
Collections.sort(list);
System.out.println("The sorted list is: "+list);
int pos = Collections.binarySearch(list, list.get(2));
System.out.println("The position of the searched element is : "+pos
+
" and the element is:"+list.get(2));
}
catch(Exception e){}

}
}

Output of this program:

C:\nisha>java SearchDemo this is a commandline argument
The sorted list is: [a, argument, commandline, is, this]
The position of the searched element is : 2 and the element is:commandline

C:\nisha>

Friday, February 3, 2012

Sorting Algorithm:

import java.util.*;

public class SortDemo {
public static void main(String[] args) {
List list = Arrays.asList(args);
Collections.sort(list);
System.out.println(list);
}
}

Advanced java

The Advanced Java/J2EE Tutorial by Gopalan Suresh Raj

my.execpc.com/~gopalan/java/java_tutorial.html
70+ items – Learn more about JavaBeans, JDO, Visual Programming, ...
A Detailed Comparison of CORBA, DCOM and Java/RMI
MTS vs. EJB (with specific code examples)

Sunday, December 26, 2010