Archive for the ‘Utility Classes’ Category

Efficient use of add(0,object) method of java.util.List

August 22, 2009

If you want an efficient access of add(0,object) method of List interface, where quick and random access of the list is not a primary concern. You must use java.util.LinkedList instead of ArrayList,LinearList and Queue.

You can check the efficiency of LinkedList inplementation by the given example:

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class EfficientList
{

/**
* @author Prabir Karmakar
*/
public static void main(String[] args)
{
List list = new ArrayList();
System.out.println(“Using ArrayList..”);
System.out.println(“Before Manupulation:”
+System.currentTimeMillis());
for(int i=0;i<10000;i++)
{
list.add(0, “prabir”+i);
}
System.out.println(“After Manupulation:”
+System.currentTimeMillis());

List list1 = new LinkedList();
System.out.println(“Using LinkedList..”);
System.out.println(“Before Manupulation:”
+System.currentTimeMillis());
for(int i=0;i<10000;i++)
{
list1.add(0, “raj”+i);
}
System.out.println(“After Manupulation:”
+System.currentTimeMillis());
}
}

Program Output

Using ArrayList..
Before Manupulation:1250946828955 (current time Millis)
After Manupulation:1250946829024 (current time Millis)
Using LinkedList..
Before Manupulation:1250946829024 (current time Millis)
After Manupulation:1250946829034 (current time Millis)

Advertisements

Printing from Java Program

August 8, 2009
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
public class TestPrinter
{
public static void main(String[] args)
{
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
PrintService[] pservices = PrintServiceLookup.lookupPrintServices(flavor, aset);
int printnbr = 0;
DocPrintJob pj = pservices[printnbr].createPrintJob();
try
{
FileInputStream fis = new FileInputStream(“C:\\YServer.txt”);
Doc doc = new SimpleDoc(fis, flavor, null);
pj.print(doc, aset);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}

Format Date/Time Using System package

August 3, 2009
You can easily format date/Time using System package in java.
public class PrintDateTime
{
public static void main(String [] arg)
{
//printf is not line feed and carriage return, so you have to put a line break.
System.out.printf(“Today is: %1$tm/%1$te/%1$tY”, Calendar.getInstance());
System.out.print(“\n”);
System.out.printf(“Time is: %tr”, Calendar.getInstance());
System.out.print(“\n”);
System.out.printf(“Time is: %tT”, Calendar.getInstance());
}
}
Here
  • t means, you want to deal with date/time.
  • m means, you want month from the date.
  • e means, you want day from the date.
  • Y means, you want Year from the date.
  • r means, you want time as 12-hour clock with AM/PM
  • T means, you want time as 24-hour clock.
Output:
Today is: 08/3/2009
Time is: 09:55:45 PM
Time is: 21:55:45

Formating String using String Class

August 3, 2009
public class FormatString
{
public static void main(String [] arg)
{
Object ob[] = {“prabir”,27};
st = String.format(“My name is %s, I am %d years old”, ob);
System.out.println(st);
st = String.format(“The value of PI is:%f”, Math.PI);
System.out.println(st);
//specify no. of decemals
st = String.format(“The value of PI is:%.2f”, Math.PI);
System.out.println(st);
}
}
Here
  • s expecting string value.
  • d expecting numeric value without decimal.
  • f expecting float value.
  • .2 specify no of decimal places.
Output:
The value of PI is: 3.141593
The value of PI is: 3.14

Reading file with Scanner

August 1, 2009

You can easily use Scanner Class to read a physical file, you can refer given example:
public class ReadFile
{
private Scanner fileScanner = null;
public ReadFile()
{
this(null);
}
public ReadFile(File fileName)
{
if(fineName==null)
{
throw new NullPointerException(“File can not be null.”);
}
fileScanner = new Scanner(fileName);
//use line separator delimiter for fetch one by one line from the file, if you don’t it fetch one by one word.
fileScanner.useDelimiter(Constant.LINE_SEP);
}
public void read()
{
while(fileScanner.hasNext())
{
System.out.println(fileScanner.next());
}
fileScanner.close();
}
public static void main(string [] arg)
{
try
{
File file = new File(arg[0])
ReadFile fileReader = new ReadFile(file);
fileReader.read();
}
catch(FileNotFoundException ex)
{
ex.printStack();
}
}
}

use this this command:
java ReadFile data.txt

Create Read Only List

July 30, 2009

You can create read only List using Collections, complete code is given bellow:

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

/*
* @author: Prabir Karmakar
*/

public class UnModifiable
{
   private List list = null;
   private List fixed = null;

   public void initializeList(String args[])
       throws Exception
   {
      if(args.length<=0)          throw new Exception("Empty String: please enter string");       list = new ArrayList();
      for(String elem : args)
      {
         list.add(elem);
      }
   }

   public void createUnmodifiableList()
   {
     fixed = new ArrayList();
     fixed = Collections.unmodifiableList(list);
   }

   public void doSomeChange(String str)
   {
     if(fixed==null)
       throw new NullPointerException(“Read-Only list not initialized.”);
     try
     {
       fixed.add(str);
     }catch(UnsupportedOperationException uox)
     {
        throw new UnsupportedOperationException(“Can’t modify readonly list.”);
     }
   }

   public void fetch()
   {
     for(String str : list)
     {
       System.out.println(str);
     }
   }

   public static void main(String arg[])
   {
     UnModifiable unList = new UnModifiable();
     String param[] = {“prabir”,”rahul”,”kumar”};
     try
     {
       unList.initializeList(param);
       unList.createUnmodifiableList();
       unList.fetch();
       unList.doSomeChange(“raj”);
      }catch(Exception ex)
      {
        System.out.println(ex.getMessage());
      }
   }
}

Use Of Scanner Class

July 28, 2009

Java 5 provides a utility class named Scanner which is very power full for parsing/Tokening any strings, Input Streams, Files, Channels.

Do not compare it with StringTokenizer utility class, this is only working with strings.

One Important feature of Scanner class is that you can parse any primitive datatype from the given strings, Input Streams, Files and Channels. 

e.g: suppose i want to take only number from the command line(InputStream), then you can use this class. the implementation of this class is very simple, there are getter methods for almost all primitive datatypes.

The constructor can take String, InputStream, File etc.

public class TestScanner

{

  public static void main(String arg[])

  {

    Scanner scan = new Scanner(System.in);

    int retNum = scan.nextInt();

    System.out.println(“Yaaaa , You Have Entered :”+ retNum);

  }

}

Default delimiter for Scanner is space between two words. if you want to use another delimiter then you have to set the delimiter for that Scanner, use this Syntax:

scanner.useDelimiter(“,”);

e.g: if i want to get all boolean values from the scanner, then

public class FetchBooleanScanner

{

  public static void main(String arg[])

  {

    Scanner scan = new Scanner(“prabir,2,true,prabirmj,3,false,raj,4,false”);

    scan.useDelimiter(“,”);

    while(scan.hasNext())

    {

        if(scan.hasNextBoolean())

        {

           System.out.println(scan.nextBoolean());

         }

         else

         {

             scan.next();

          }

    }

  }

}

Scanner can also operate with Regular Expression using scanner object method findInLine().

public class TestScannerRegEx

{

  public static void main(String arg[])

  {

    String input = “1 persion 2 persion black  persion white persion”; 

    Scanner scan = new Scanner(input);

    scan.findInLine(“(\\d+) persion (\\d+) persion (\\w+) persion (\\w+)”);

    MatchResult result = scan.match();

    for (int i=1; i<=result.groupCount(); i++)

        System.out.println(result.group(i));

    scan.close(); 

  }

}