"Before software can be reusable it first has to be usable"- Ralph Johnson

Monday, November 21, 2011

Deque and ArrayDeque

By 10:55 AM
Deque is the abbreviation of “Double Ended Queue”. A Collection that allows us to add (or) remove elements at both ends. Deque supports total size of collection for both fixed and unspecified size limits.

Deque implementation can be used as Stack(Last in first out ) or Queue(First in First Out). For each insertion, retrieval and removal of elements from deque there exists methods in 2 flavours. One will throw exception if it fails in an operation and another one returns status or special value for each operation.

OperationSpecial value methodException throwing method
Insertion at headofferFirst(e)addFirst(e)
Removal at headpollFirst()removeFirst()
Retrieval at Head
peekFirst()getFirst()
Insertion at TailofferLast(e)addLast(e)
Removal at TailpollLast()removeLast()
Retrieval at Tail
peekLast()getLast()

Implementation of Deque doesn’t require preventing the insertion of null, but when we are using special value method null is return to indicate that collection is empty. So it is recommendable not to allow insertion of null.

ArrayDeque is a class that implements Deque. It has no capacity restrictions. It will perform faster than stack when used as stack and faster than linked list when used as queue. ArrayDeque is not thread Safe. The following example explains how to write program using ArrayDeque.

Example:
import java.util.ArrayDeque;
import java.util.Iterator;


public class DequeExample
{
public static void main(String as[])
{
ArrayDeque adObj = new ArrayDeque(); 


//Insertion by using various methods
adObj.add("Oracle"); 
adObj.addFirst("DB2");
adObj.offerFirst("MySQL");   //returns boolean - true R false 
adObj.offerLast("Postgres");   //returns boolean - true R false

//Retrievals 
System.out.println("Retrieving First Element :" + adObj.peekFirst());
System.out.println("Retrieving Last Element  :"+ adObj.peekLast());


//Removals
System.out.println("Removing First  Element  :"+ adObj.pollFirst());
System.out.println("Removing Last  Element   :"+ adObj.pollLast());


//Reverse traversal
System.out.println("Remaining Elements :");
Iterator it = adObj.descendingIterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}


Output:
Retrieving First Element :MySQL
Retrieving Last Element  :Postgres
Removing First  Element  :MySQL
Removing Last  Element   :Postgres
Remaining Elements :
Oracle
DB2


For more please visit- http://download.oracle.com/javase/6/docs/api/java/util/ArrayDeque.html
Read More...

What's New in Java 6.0 Collection API

By 10:35 AM
Here we have the new Collections APIs introduced in Java 6.0. There are few interesting changes in the Collections APIs, one amoung them is the Deque. Deque is used for the Bi-Directional traversal. It has different implementations including BlockingDeque,ArrayDeque,etc. Let's talk about the Deque and its various implementation, also few more changes in the Collectiona API in Java 6.0

Following are the new collection APIs introduced in Java 6.0. And the list of Interfaces and classes are given below.


New Interfaces:

  • Deque
  • BlockingDeque
  • NavigableSet
  • NavigableMap

New Classes:

  • ArrayDeque
  • LinkedBlockingDeque
  • ConcurrentSkipListSet
  • ConcurrentSkipListMap
  • AbstractMap.SimpleEntry
  • AbstractMap.SimpleImmutableEntry
And following are the updated Classes in Java 6.0
  • LinkedList
  • TreeSet
  • TreeMap
  • Collections
Read More...

Friday, September 23, 2011

Simple Word Replacement From A String Using Regular Expression

By 1:37 AM
Here is a class which replace some words from a given string using Regular Expression.
/*
 * This code writes "One dog, two dogs in the yard."
 * to the standard-output stream:
 */
import java.util.regex.*;

public class Replacement {
    public static void main(String[] args) 
                         throws Exception {
        // Create a pattern to match cat
        Pattern p = Pattern.compile("cat");
        // Create a matcher with an input string
        Matcher m = p.matcher("one cat," +
                       " two cats in the yard");
        StringBuffer sb = new StringBuffer();
        boolean result = m.find();
        // Loop through and create a new String 
        // with the replacements
        while(result) {
            m.appendReplacement(sb, "dog");
            result = m.find();
        }
        // Add the last segment of input to 
        // the new String
        m.appendTail(sb);
        System.out.println(sb.toString());
    }
}
Read More...

Search For Any Comment Line in a .java File Using Regular Expression

By 12:24 AM
The following class searches for the line which are being commented in a file called "Test.java".
 /*
 * Prints out the comments found in a .java file.
 */
import java.util.regex.*;
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.nio.channels.*;

public class CharBufferExample {
    public static void main(String[] args) throws Exception {
        // Create a pattern to match comments
        Pattern p = 
            Pattern.compile("//.*$", Pattern.MULTILINE);
        
        // Get a Channel for the source file
        File f = new File("Test.java");
        FileInputStream fis = new FileInputStream(f);
        FileChannel fc = fis.getChannel();
        
        // Get a CharBuffer from the source file
        ByteBuffer bb = 
            fc.map(FileChannel.MAP_RO, 0, (int)fc.size());
        Charset cs = Charset.forName("8859_1");
        CharsetDecoder cd = cs.newDecoder();
        CharBuffer cb = cd.decode(bb);
        
        // Run some matches
        Matcher m = p.matcher(cb);
        while (m.find())
            System.out.println("Found comment: "+m.group());
    }
}

Read More...

Removing Control Characters from a File Using Regular Expression

By 12:17 AM
Here we have a sample class which will remove all the control characters from a file. 
/* This class removes control characters from a named
*  file.
*/
import java.util.regex.*;
import java.io.*;

public class Control {
    public static void main(String[] args) 
                                 throws Exception {
                                 
        //Create a file object with the file name
        //in the argument:
        File fin = new File("fileName1");
        File fout = new File("fileName2");
        //Open and input and output stream
        FileInputStream fis = 
                          new FileInputStream(fin);
        FileOutputStream fos = 
                        new FileOutputStream(fout);

        BufferedReader in = new BufferedReader(
                       new InputStreamReader(fis));
        BufferedWriter out = new BufferedWriter(
                      new OutputStreamWriter(fos));

	// The pattern matches control characters
        Pattern p = Pattern.compile("{cntrl}");
        Matcher m = p.matcher("");
        String aLine = null;
        while((aLine = in.readLine()) != null) {
            m.reset(aLine);
            //Replaces control characters with an empty
            //string.
            String result = m.replaceAll("");
            out.write(result);
            out.newLine();
        }
        in.close();
        out.close();
    }
}
Read More...

Usage of "Final" keyword in Java

By 12:11 AM
No matter how  often we use final keyword in our Java program, but we should use the final keyword liberally to communicate our intent.

The final keyword has more than one meaning :
  • A final class cannot be extended.
  • A final method cannot be overridden.
  • A final field, parameter and local variable cannot change their value once set.
In the last case, "value" for primitives is understood in the usual sense, while "value" for objects means the object's identity, not its state. Once the identity of a final object reference is set, it can still change its state, but not its identity.

Declaring primitive fields as final automatically ensures thread-safety for that field.
Some habitually declare parameters as final, since this almost always the desired behaviour. Others find this verbose, and of little real benefit.

Consistently using final with local variables (when appropriate) can be useful as well. It brings attention to the non-final local variables, which usually have more logic associated with them (e.g:- result variables, accumulators, loop variables). Many find this verbose. A reasonable approach is to use final for local variables only if there is at least one non-final local variable in the method ; this serves to quickly distinguish the non-final local variables from the others.

So here have the advantages of using final :
  • Clearly communicates your intent
  • Allows the compiler and virtual machine to perform minor optimizations
  • Clearly flags items which are simpler in behavior - final says,  "If you are looking for complexity, you won't find it here."
Read More...

Sunday, September 18, 2011

Simplest Way To Connect To A Shared Folder in Windows With Java

By 10:08 AM
Sometimes we usually meet a situation like, we want to access a shared folder in windows environment remotely. So this is one of the simplest way to do so :-
    File file = new File("\\\\theRemoteIP\\webapps"); 
    File[] files = file.listFiles();  
    System.out.println("Access granted");  

    for (int i = 0; i < files.length; i++)  
    {  
        String fname = files[i].getName();  
        System.out.println(fname);  
    }
Read More...

Saturday, September 10, 2011

New Features Of JDK 7

By 2:53 AM


With JDK 7 out the door, many writeups of the release have naturally focused on its larger features like Project Coin, NIO.2, the fork/join framework, and invokedynamic. However, there are a number of small but useful library conveniences in JDK 7 that shouldn't be overlooked.
  • To allow more informative assertion errors to be constructed, AssertionError now includes a constructor taking a string message and a Throwable cause, which is one of the four conventional constructors for exception types.
  • The methods which convert strings to numeric values differed in whether or not a leading plus, "+", was regarded as valid input. Float, Double, and BigDecimal accepted a leading plus while Byte, Short, Integer, Long, and BigInteger did not. As of JDK 7, all those types consistently accept a leading plus in their parseFoo, valueOf, and decode methods.
  • To help write more efficient comparators, Boolean, Byte, Character, Short, Integer, and Long each have a two-argument static compare method that performs the desired comparison operation without boxing overhead.
  • This six checked exception types that can be thrown by core reflection now have a common supertype, ReflectiveOperationException. This additional type complements the improved exception handling available with multi-catch and more precise re-throw from Project Coin.
  • The java.util.Objects class contains a number of small, but commonly used methods, many of them for coping with null inputs. For example, Objects contains a two-argument static equals method which does the right thing on null inputs. I've replaced a half-dozen copies of that method's logic in the JDK; I'm sure many more instances can be removed in other code bases as JDK 7 is adopted.
  • Part of NIO.2, I expect over time the utility methods in java.nio.file.Files to copy, read, and write the contents of file will see heavy usage.
And To recall, these are the list of feature which we discussed :-

  • Modularity
  • Multi-Language Support
  • New Garbage Collector
  • NIO.2 New File System API
  • Additional Swing API
Read More...