Friday, August 20, 2010

Java Hints

Software Engineering
http://best-practice-software-engineering.ifs.tuwien.ac.at/

Decompiler .java

jar -xf comirva-src-0.3.jar

Enum Error --> downgrade java 1.4
Project -> Properties -> Java Compiler -> Compiler compliance level) to be 1.4 or under? You need 1.5 (5.0) or 1.6 (6.0) for enum declarations to be correct.

Mig Layout Java - Desktop Application

http://www.miglayout.com/

Diagram for Hierarchy of Exception Classes


Hierarchy of Exception Classes

Java default vs protected access

java protected and default

Diagram to show java string’s immutability

java_string_immutability
http://best-practice-software-engineering.ifs.tuwien.ac.at/index.html
http://best-practice-software-engineering.blogspot.com/

Eclipse

eclipse.ini
Set jre classpath for eclipse
-vm
c:/java/jdk16012/jre/bin/javaw.exe

Java Alamanac
http://www.exampledepot.com/
www.java2s.com

Get Current Directory
File templateDir = new File (".");
System.out.println(templateDir.getCanonicalPath() + "\\web\\templates\\");


Another app data

  • Local AppData (C:\Documents and Settings\USER\Local Settings\Application Data)
  • Local Settings (C:\Documents and Settings\USER\Local Settings)
  • AppData (C:\Documents and Settings\USER\Application Data)

System.getProperty("user.home")
File f = new File(System.getenv("AppData"+"Mozilla/Firefox/Profiles"));


Jena - schemagen.java
//args = new String[] { "-i", "G:/java/appjava/netbeansapp/org.owls.gapi/src/eowl/music.owl" ,"--ontology","--uppercase"};
args = new String[] { "-i", "C:/AppServ/www/Ontology/mysws/MyResource.owl" ,"--owl","--uppercase","--package", "vocabularies","-o", "C:/AppServ/www/Ontology/mysws"};

call a webserivce from a Jsp page

Preconditions:
You have working WebService and know its URI
(I used http://localhost:8080/helloservice/hello, installed on my machine)
 
Steps:
SECTION 1. Stubs creation. 
1. Add Axis libs into CLASSPATH. For me it was:
<Axis_1_3_home>/lib/axis.jar:<Axis_1_3_home>/lib/commons-logging-1.0.4.jar:<Axis_1_3_home>/lib/commons-discovery-0.2.jar:<Axis_1_3_home>/lib/jaxrpc.jar:<Axis_1_3_home>/lib/saaj.jar:<Axis_1_3_home>/lib/wsdl4j-1.5.1.jar
 
2. Genearte stubs.
java org.apache.axis.wsdl.WSDL2Java <WS_URI>?wsdl
For me it was:
java org.apache.axis.wsdl.WSDL2Java http://localhost:8080/helloservice/hello?wsdl
 
After that you will have Java Stubs generated accrding to WSDL in your current 
directory. For me it was:
./helloservice/endpoint/HelloPortBindingStub.java
./helloservice/endpoint/HelloService.java
./helloservice/endpoint/Hello.java
./helloservice/endpoint/HelloServiceLocator.java
 
 
3. Compile stubs. In my case it was:
javac -d . helloservice/endpoint/*.java

4. Test that stub is working by simple command line client:
(name it Main.java, compile and execute)
----------------------------
import helloservice.endpoint.*;

public class Main {
public static void main(String[]args) throws Exception{
String name="My Name :)";
HelloService service = new HelloServiceLocator();
Hello port = service.getHelloPort();
String response = port.sayHello(name);
System.out.println(response);

}

}
---------------------------

So now we are going to create WebApp client (Jsp or Servlet)

SECTION 2. WS Jsp/Servlet client using Axis


1. Create directory:
<wb_root>/WEB-INF/lib

2. Copy everything from <Axis_1_3_home>/lib/ to <wb_root>/WEB-INF/lib directory
3. Jar your stubs (jar -cvf hellostub.jar helloservice/) and also copy to <wb_root>/WEB-INF/lib
4. Create index.jsp in the <wb_root>:
index.jsp:
--------------------------------------------
<%@ page import="helloservice.endpoint.HelloServiceLocator,helloservice.endpoint.Hello, helloservice.endpoint.HelloService" %>
<html><body>
Text: 
<% 
HelloService service = new HelloServiceLocator();
Hello port = service.getHelloPort();
String resp = port.sayHello(request.getParameter("username")); 
%>
<h2><font color="black"><%=resp%></font></h2>
</body>
</html>
--------------------------------------------
5. Create web.xml file in <wb_root>/WEB-INF/
--------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app 
xmlns="http://java.sun.com/xml/ns/javaee" 
version="2.5" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>webclient</display-name>
</web-app>
---------------------------------------------
6. Simple copy your web app into <tomcat>/webapps/
For me it was:
cp -r <wbroot>/* <tomcat>/wcc


7. Test your client in browser by typing:
http://localhost:8080/wcc/index.jsp

Or,(to pass parameter in my case),

http://localhost:8080/wcc/index.jsp?username=Guest


ERRORS
'
Access restriction: The type is not accessible due to restriction on required library xxx.jar' (perhaps using some combination of Eclipse 3.4 and/or JDK 6 update 10?),
You need to go into the Build Path for the project, Libraries tab, select the JRE System Library, and add an access rule, "Accessible, **".


CONVERT STRING TO BOOLEAN
        String strBoolean = "true";
        boolean theValue = Boolean.parseBoolean(strBoolean);
      
READ DIR & List Files
    File dir = new File("owls");
         String [] fileNames = dir.list(); //List FileName
         File [] fileObjects= dir.listFiles(); //List FileObject
         for (int i = 0; i < fileObjects.length; i++) {
             if(!fileObjects[i].isDirectory()){
                 System.out.println(fileNames[
                 System.out.println(fileObjects[i].length());
             }
         }

String.startsWith("http:") ) return new HttpURLConnection();
else if( String.startsWith("ftp:") ) return new FtpURLConnection();

Recursive List

Here is an example of listing files and directories recursively.
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
// File   : io/file/RecusiveList.java
// Purpose: Recursively list directories and files.
// Author : Fred Swartz 1997-08-06 (Bangkok, Thailand), 2000-10-31 (Rota, Spain)
//                      2006-09-25 (Rodenbach, Deutschland)

import java.util.*;
import java.io.*;

public class RecursiveList {
static final int      MAX_DEPTH  = 20;  // Max 20 levels (directory nesting)
static final String   INDENT_STR = "   ";                 // Single indent.
static final String[] INDENTS    = new String[MAX_DEPTH]; // Indent array.

//===================================================================== main
public static void main(String[] args) {
//... Initialize array of indentations.
INDENTS[0] = INDENT_STR;
for (int i = 1; i < MAX_DEPTH; i++) {
INDENTS[i] = INDENTS[i-1] + INDENT_STR;
}

System.out.print("Enter a directory name to list recursively:");
Scanner in = new Scanner(System.in);
File root = new File(in.nextLine());
if (root != null && root.isDirectory()) {
listRecursively(root, 0);
} else {
System.out.println("Not a directory: " + root);
}
}


//========================================================== listRecursively
public static void listRecursively(File fdir, int depth) {
System.out.println(INDENTS[depth] + fdir.getName());  // Print name.

if (fdir.isDirectory() && depth < MAX_DEPTH) {
for (File f : fdir.listFiles()) {  // Go over each file/subdirectory.
listRecursively(f, depth+1);
}
}
}
}

java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String

Very simply, you get the exception
java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String
when you try to cast an array kind of a class to the linear type. In this case, attempting to cast String -> String[] or vice versa will cause the JVM to throw this particular exception at runtime. Compilers cannot catch this oversight.
As an example, consider an attempt to read all parameters passed to a servlet using the request object. The parameter map can be obtained with:
Map parameters = request.getParameterMap();

From HTML basics, we know that parameters are passed as key/value pairs of Strings to the web server, so the temptation is to assume that the generics mapping for parameters is <String, String>. In fact, compilers will allow you to use this generic:
Map<String,String> parameters = request.getParameterMap();
for(String key: parameters.keySet()) {
String value = parameters.get(key); // error happens here
System.out.println(key + "=" + value);
}

This code snippet will compile and run fine, producing results that look like:
firstName=[Ljava.lang.String;@1fe49b5
lastName=[Ljava.lang.String;@1993b4f
This is assuming parameters passed to the servlet (or JSP) include ones named 'firstName' and 'lastName', of course.

As it turns out, the value side of the parameter map is actually a String[] type. So the proper generic for this map is <String, String[]>. When you call request.getParameter("firstName");, it simply returns the equivalent of parameters.get(key)[0];, which reads the first value associated with the key. This happens even if your form might have sent single-dimension parameters for processing.
So, just remembering the map's generics mapping may save you a lot of headaches down the road. This is simple Java internals - but a look at forums on the web shows how much of a problem this is for programmers out there. You's get the same kind of exception if you attempted to cast Date to Date[] (which would throw java.lang.ClassCastException: java.util.Date cannot be cast to [Ljava.util.Date;).

Dealing with nulls

UtilFactory.convertNull


Java – comparing strings

Use == for primitive data types like int
If (mystring == null)

Use the equals() method to compare objects
Use .equals for strings  : if (a.equals(“cat”))

Java - Converting int to string


String myString = Integer.toString(my int value)
   or
   String str = "" + i

Java - Converting String to int


int i = Integer.parseInt(str);
   or
int i = Integer.valueOf(str).intValue();


List String to Array String


List<String> tokenList = Tokenizer.wordsToList(sentence);
String[] tokenArray = (String[]) tokenList.toArray();


double to String :
   String str = Double.toString(i);

long to String :
String str = Long.toString(l);


float to String :
String str = Float.toString(f);


String to double :
double d = Double.valueOf(str).doubleValue();

String to long :
long l = Long.valueOf(str).longValue();
   or
   long l = Long.parseLong(str);

String to float :
float f = Float.valueOf(str).floatValue();

decimal to binary :
   int i = 42;
   String binstr = Integer.toBinaryString(i);

decimal to hexadecimal :
   int i = 42;
   String hexstr = Integer.toString(i, 16);
 
   or
   String hexstr = Integer.toHexString(i);
 
   or (with leading zeroes and uppercase)
   public class Hex {
     public static void main(String args[]){
       int i = 42;
       System.out.print
         (Integer.toHexString( 0x10000 | i).substring(1).toUpperCase());
      }
     }


hexadecimal (String) to integer :
int i = Integer.valueOf("B8DA3", 16).intValue();
   or
   int i = Integer.parseInt("B8DA3", 16);    


ASCII code to String
int i = 64;
   String aChar = new Character((char)i).toString();

integer to ASCII code (byte)
char c = 'A';
   int i = (int) c; // i will have the value 65 decimal


integer to boolean
   b = (i != 0);

boolean to integer
i = (b)?1:0;

Java Validate Credit Card

- http://www.rgagnon.com/javadetails/java-0034.html
- http://www.codeproject.com/KB/aspnet/wdxcreditcardvalidation.aspx


String Array

static String [] sw={  "a", "able", "about"}
public static String[] getStopWordList() {return(sw);}




public class Stopwords
{

        public static  Vector removeSW(Vector vm)
        {
                List sw;
                sw=Arrays.asList(stopList.getStopWordList());
                Vector v=new Vector();
                for(int i=0;i<vm.size();i++)
                {
                        if((sw.contains(vm.elementAt(i))) |((vm.elementAt(i)).toString()).matches("[0-9]+"))
                        {
                        }
                        else
                        {
                                v.addElement(vm.elementAt(i));
                        }
                }
                return(v);
        }

}


The collection classes in java.util include some of the most commonly used classes in Java. The most commonly used collection types are List and Map. Concrete implementations of List include ArrayList and Vector, which are variable size lists ideal for building, storing and manipulating a list of elements of any type of object. Lists are ideal when you want to access elements by numerical index.
Maps provide a more general way of storing elements. The Map collection type allows you to store pairs of elements, termed "keys" and "values", where each key maps to one value. Conceptually, you could consider Lists as Maps which have numeric keys. However in practice there no direct connection between Lists and Maps except that they are both defined in java.util. In this article, we will focus on the Maps that are available with the core Java distribution, and also consider how to adapt or implement specialized Maps that are more optimal for your application specific data.

String Comparison

Strings can not be compared with the usual <, <=, >, or >= operators, and the == and != operators don't compare the characters in the strings.

Comparing Strings: ==, .equals(), .compareTo(), ...
To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object. Two strings may be different objects, but have the same value (have exactly the same characters in them). Use the .equals() method to compare strings for equality. Similarly, use the .compareTo() method to test for unequal comparisons. For example,
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // CORRECT>
String Arrays
Java 5 finally introduced support for printing out arrays. The java.util.Arrays utility class has methods for providing a pretty toString for any shape array, including
String[] arry = new String[] { "Test", "Array", "toString" };
// prints out [Test, Array, toString]
System.out.println(Arrays.toString(arry));
You may notice that the output of these methods matches up closely to the output of the standard list implementations in the collections API.
If you have a multi-dimensional array, you may and you want all of the arrays in that multi-dimensional array to print out, you can use the alternative method - deepToString :
String[][] arry = new String[][] {
{ "Test", "Array", "1" },
{ "Test", "Array", "2" },
{ "Test", "Array", "3" }
};
// prints out:
// [[Test, Array, 1], [Test, Array, 2], [Test, Array, 3]]
System.out.println(Arrays.deepToString(arry));

Print Array

for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
Question:How do I convert a String to a float with Java?
Answer:
Converting a String to a float requires that you first convert the String to a Float object, then convert the Float object to a float data type (Float is an object, while float is a primitive data type).
An example of a simple program that performs this conversion is shown below:
public class s2f {

public static void main (String[] args) {

// String s = "fred"; // do this if you want an exception

String s = "100.00";

try {
float f = Float.valueOf(s.trim()).floatValue();
System.out.println("float f = " + f);
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}

}

}

Other notes
  • Float.toString(float f) is used to convert in the other direction, from a float to a String.


Array & List

                //String[] listProperties = new String[100];
List list = new ArrayList();
//int index = 0;
for (ExtendedIterator j = ocl.listDeclaredProperties(); j.hasNext();) {
                 list.add(j.next().toString());
                 //System.out.println((OntProperty) j.next());
//System.out.println(index + j.next().toString());
//listProperties[index]= j.next().toString();
//index = index + 1;
}
String[] array = (String[]) list.toArray(new String[list.size()]);
System.out.println(Arrays.toString(array));

Duyệt List

List li = oclass.getDeclaredProperties();
    ListIterator k = li.listIterator(li.size());
while (k.hasPrevious()) {
Object element = k.previous();
System.out.println("Properties: " + element.toString());
}

Property[] list = new Property[100];
for (ExtendedIterator j = ocl.listDeclaredProperties(); j.hasNext();) {
String y = j.next().toString();
String xyz = y.substring(Foaf.getURI().length());
System.out.print(xyz);
list[index]= (Property) j.next();
index = index + 1;
}

Generate pairs of random Sentence
        String[] articles = { "a", "the", "an", "one", "the first" };
        String[] noun1 = { "cat", "dog", "sun", "rain", "boot" };
        String[] verb = { "sit", "catch", "stab", "chase", "cuddle" };
        String[] noun2 = { "summer", "gun", "chair", "bag", "woman" };
        Random r = new Random();
        for (int i = 1; i <= 10; i++) {
            int selectedElement = r.nextInt(articles.length);
            int selectedElement2 = r.nextInt(articles.length);
            String randomSentence = articles[selectedElement] + " "
                    + noun1[selectedElement] + " " + verb[selectedElement]
                    + " " + articles[selectedElement] + " "
                    + noun2[selectedElement];
            String randomSentence2 = articles[selectedElement] + " "
                    + noun1[selectedElement2] + " " + verb[selectedElement2]
                    + " " + articles[selectedElement2] + " "
                    + noun2[selectedElement2];
            System.out.println("sentence 1:" + randomSentence);
            System.out.println("sentence 2:" + randomSentence2);
        }


Lấy giá trị từ OWL Schema

RDFNode node = thisIndividual.getPropertyValue(Foaf.FAMILY_NAME);
if (node != null) {
System.out.println(node.toString());
}
DateTime in Java


GWT


The import com.gwtext cannot be resolved & Unable to find 'com/gwtext/GwtExt.gwt.xml'


<inherits name='com.gwtext.GwtExt' /> & put the gwtext.jar in the build.xm


Axis2
Options options = new Options();
options.setManageSession(true);
ServiceClient sender = new ServiceClient();
sender.setOptions(options);

MySQL Connection & Create Table

package manage;
import java.sql.*;                                                                                                                
public class DatabaseInit {
   final public static String CONN_STRING="jdbc:mysql://localhost/database";
   final public static String USERNAME = "root";
   final public static String PASSWORD = "";
   public static void createTables() throws Exception {
    Class.forName ( "org.mysql.Driver" );                                                                
    Connection conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);   
    java.sql.Statement stmt = conn.createStatement();    
    stmt.execute("CREATE TABLE user(userid VARCHAR, password VARCHAR)");
    conn.close();
    }
    public static void main(String[] args) throws Exception {
    createTables();
    }
}

Hybernate
Error
org.hibernate.QueryException: ClassNotFoundException: org.hibernate.hql.ast.HqlToken [select a.password from employee.dbbeans.LoginBean as a where a.userName = ?]
Solution is to add following property to the hibernate configuration file hibernate.cfg.xml
<property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>


TIME UNITS

import java.util.concurrent.TimeUnit;
public class TimeUnitDemo {
  public static void main(String[] args) {
    TimeUnit tu = TimeUnit.DAYS;

    System.out.println(tu.toDays(1));
    System.out.println(tu.toHours(1));
    System.out.println(tu.toMinutes(1));

  }
}


1. Date() + SimpleDateFormat()

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));

2. Calender() + SimpleDateFormat()

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
P.S Please access java documentation here to understand more date time format in SimpleDateFormat
http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class GetCurrentDateTime {
public static void main(String[] args) {

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
System.out.println(DateUtils.now("dd MMMMM yyyy"));
System.out.println(DateUtils.now("yyyyMMdd"));
System.out.println(DateUtils.now("dd.MM.yy"));
System.out.println(DateUtils.now("MM/dd/yy"));
System.out.println(DateUtils.now("yyyy.MM.dd G 'at' hh:mm:ss z"));
System.out.println(DateUtils.now("EEE, MMM d, ''yy"));
System.out.println(DateUtils.now("h:mm a"));
System.out.println(DateUtils.now("H:mm:ss:SSS"));
System.out.println(DateUtils.now("K:mm a,z"));
System.out.println(DateUtils.now("yyyy.MMMMM.dd GGG hh:mm aaa"));


//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));


}
}

import java.util.Vector;

public class VectorBenchmark1 {

  public static final int MaxSize = 100000;

  public static final int NTRIES = 10;

  public static void main(String[] args) {
    Vector v = new Vector();

    long start = System.currentTimeMillis();
    for (int i = 0; i < MaxSize; i++)
      v.add(new Integer(i));
    long end = System.currentTimeMillis();
    System.out.println("Allocating vector elements: " (end - start)
        " milliseconds");

    Integer[] integerArray = new Integer[1];
    start = System.currentTimeMillis();
    for (int i = 0; i < MaxSize; i++) {
      if (i >= integerArray.length) {
        Integer[] b = new Integer[i * 2];
        System.arraycopy(integerArray, 0, b, 0, integerArray.length);
        integerArray = b;
      }
      integerArray[inew Integer(i);
    }
    end = System.currentTimeMillis();
    System.out.println("Allocating array elements:  " (end - start)
        " milliseconds");

    start = System.currentTimeMillis();
    for (int j = 0; j < NTRIES; j++)
      for (int i = 0; i < MaxSize; i++) {
        Integer r = (Integerv.get(i);
        v.set(i, new Integer(r.intValue() 1));
      }
    end = System.currentTimeMillis();
    System.out.println("Accessing vector elements:  " (end - start)
        " milliseconds");

    start = System.currentTimeMillis();
    for (int j = 0; j < NTRIES; j++)
      for (int i = 0; i < MaxSize; i++) {
        Integer r = integerArray[i];
        integerArray[inew Integer(r.intValue() 1);
      }
    end = System.currentTimeMillis();
    System.out.println("Accessing array elements:   " (end - start)
        " milliseconds");
  }
}

Thursday, August 19, 2010

Java Collection

Collection in Java

The interface and class hierarchy for collections

Key Interfaces of the Collections Framework are:

  Collection, List, Set, SortedSet ; Map, SortedMap


 Ordered:  When a collection is ordered, it means you can iterate through the collection in a specific (not-random) order. A Hashtable collection is not ordered. An ArrayList is however ordered based on the elements index position.  LinkedHashSet keeps the order established by insertion, so the last element inserted is the last element in the LinkedHashSet.

Sorted: A sorted collection means a collection sorted by natural order. The natural order is defined by the class of the objects being sorted.


List

 List is an interface cares about the index. The one thing that List has that nonlists don't have is a set of methods related to the index like get(int index),  indexOf(),  add(int index, Object obj) etc.

ArrayList

It implements List,  gives fast iteration and fast random access. It is an ordered collection(by index), but not sorted.

Vector

Vector implements List, is basically same as ArrayList, but Vector methods are synchronized for thread safety.

LinkedList

LinkedList implements List,  is ordered by index position like ArrayList, except that the elements are doubly linked to one another. This linkage gives you new methods for adding or removing from the beginning or end, which makes an easy choice for implementing a stack or queue. It iterates more slowly than ArrayList, but a good choice for fast insertion or deletion.

Set

Set is an interface which cares for uniqueness - it does not allow duplicates.

HashSet

HashSet implements Set, is unsorted, unordered Set. It uses the hashcode of the object being inserted, so the more efficient your hashCode() implementation the better access performance you'll get. 

LinkedHashSet

LinkedHashSet implements Set, is an ordered version of HashSet that maintains a doubly linked list accross all elements.  Use this class instead of HashSet where you care of the iteration order.

TreeSet

TreeSet implements SortedSet interface, is one of two sorted collections(other is TreeMap), guarantees that the elements will be in ascending order, according to the natural order of the elements. 

Map

Map cares about unique identifiers. You map a unique ID to a specific value, where key/value pair are both objects.


Map map = new HashMap();

or

Map<String, Integer> map = new HashMap<String, Integer>();
    map = new TreeMap();

    map.put("a"new Integer(1));
    map.put("b"new Integer(2));
    map.put("c"new Integer(3));

for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
      Map.Entry entry = (Map.Entryit.next();
      Object key = entry.getKey();
      Object value = entry.getValue();
    }

HashMap

The HashMap gives you an unsorted, unordered Map. HashMap allows one null key in a collection and multiple null values in a collection.

Hashtable

Like Vector, Hashtable has been from prehistoric Java times.  Hashtable is the synchronized counterpart of HashMap. Hashtable does not allow nulls, neither as a key nor as a value.

LinkedHashMap

Like Set's counterpart LinkedHashSet, the LinkedHashMap collection maintains the insertion order. Although it is slower than HashMap for adding and removing elements,  but you can expect faster iteration with LinkedHashMap.

TreeMap

TreeMap is a sorted Map.  TreeMap lets you pass you own comparison rules


1. Use Vector if there are multiple threads and ArrayList if there is only a single thread.
2. Use Hashtable if there are multiple threads and HashMap if there is only a single thread.
3. Use StringBuffer if there are multiple threads and StringBuilder if there is only a single thread.

Eg: Prefer using,
List list = new Vector()
or
List list = Collections.synchronizedList(new ArrayList);

instead of
Vector list = new Vector();

The first two allows the code to be more flexible.

import java.util.ArrayList;

import java.util.Collection;

import java.util.HashMap;

import java.util.HashSet;

import java.util.Iterator;

import java.util.LinkedHashMap;

import java.util.LinkedHashSet;

import java.util.LinkedList;

import java.util.List;

import java.util.Map;

import java.util.Set;

import java.util.SortedMap;

import java.util.SortedSet;

import java.util.TreeMap;

import java.util.TreeSet;


public class CollectionAll {

  public static void main(String[] args) {

    List list1 = new LinkedList();

    list1.add("list");

    list1.add("dup");

    list1.add("x");

    list1.add("dup");

    traverse(list1)

    List list2 = new ArrayList();

    list2.add("list");

    list2.add("dup");

    list2.add("x");

    list2.add("dup");

    traverse(list2)

    Set set1 = new HashSet();

    set1.add("set");

    set1.add("dup");

    set1.add("x");

    set1.add("dup");

    traverse(set1)

    SortedSet set2 = new TreeSet();

    set2.add("set");

    set2.add("dup");

    set2.add("x");

    set2.add("dup");

    traverse(set2)

    LinkedHashSet set3 = new LinkedHashSet();

    set3.add("set");

    set3.add("dup");

    set3.add("x");

    set3.add("dup");

    traverse(set3)

    Map m1 = new HashMap();

    m1.put("map""Java2s");

    m1.put("dup""Kava2s");

    m1.put("x""Mava2s");

    m1.put("dup""Lava2s");

    traverse(m1.keySet())

    traverse(m1.values())

    SortedMap m2 = new TreeMap();

    m2.put("map""Java2s");

    m2.put("dup""Kava2s");

    m2.put("x""Mava2s");

    m2.put("dup""Lava2s");

    traverse(m2.keySet())

    traverse(m2.values())

    LinkedHashMap /* from String to String */m3 = new LinkedHashMap();

    m3.put("map""Java2s");

    m3.put("dup""Kava2s");

    m3.put("x""Mava2s");

    m3.put("dup""Lava2s");

    traverse(m3.keySet())

    traverse(m3.values())

  }


  static void traverse(Collection coll) {

    Iterator iter = coll.iterator();

    while (iter.hasNext()) {

      String elem = (Stringiter.next();

      System.out.print(elem + " ");

    }

    System.out.println();

  }


}


//            ListIterator ref = reference.listIterator();
//            int i=0;
//            while (ref.hasNext()){
//                System.out.println(i+"-"+ref.next());                
//                i++;
//                SomNode iter = (SomNode) ref.next();
//                
//            }
//            
            
//            Iterator<SomNode> iter = reference.iterator();
//            while (iter.hasNext()) {
//                for (int j = 0; j < iter.next().getValues().length; j++) {
//                    System.out.println(j+"+"+iter.next().getValues()[j] + ",");
//                }
//                System.out.println();
//            }



How to merge two Array List containing Objects   
public class MyObject {

private String name;
private int age;

public MyObject() {
}

public MyObject(String name, int age) {
this.name = name;
this.age = age;
}

//setter and getter for name & age


public boolean equals(Object obj) {
if(obj == null) {
return false;
}
if( !(obj instanceof MyObject)) {
return false;
}
MyObject newObject = (MyObject) obj;
return this.name.equals(newObject.name);
}

}


Test Code:

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

public abstract class TestMyObject {

/
@param args
loganathank
void

*/
public static void main(String[] args) {
MyObject obj1 = new MyObject("obj1",1);
MyObject obj2 = new MyObject("obj2",1);
MyObject obj3 = new MyObject("obj3",1);
MyObject obj4 = new MyObject("obj4",1);

List L1 = new ArrayList();
L1.add(obj1);
L1.add(obj2);
L1.add(obj3);

List L2 = new ArrayList();
L2.add(obj4);
L2.add(obj2);
L2.add(obj3);

Iterator l2Iterator = L2.iterator();
while(l2Iterator.hasNext()) {
Object obj = l2Iterator.next();
if(!L1.contains(obj)) {
L1.add(obj);
}
}
System.out.println(" L1.size " + L1.size());
}


}

Java - Json

http://code.google.com/p/json-simple/

System
.out.println("=======decode=======");
               
 
String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
 
Object obj=JSONValue.parse(s);
 
JSONArray array=(JSONArray)obj;
 
System.out.println("======the 2nd element of array======");
 
System.out.println(array.get(1));

  JSONObject me = array.optJSONObject(0);

JSONObject fbook = new JSONObject(s);
fbook.get("namestring");


//Manage JSON String={\"4\":[5,{\"6\":7}]};
public Map parseJSONStr(String jsonText) {
        JSONParser parser = new JSONParser();
        ContainerFactory containerFactory = new ContainerFactory() {
            public List creatArrayContainer() {
                return new LinkedList();
            }

            public Map createObjectContainer() {
                return new LinkedHashMap();
            }
        };
        try {
            Map json = (Map) parser.parse(jsonText, containerFactory);
            return json;
            // Iterator iter = json.entrySet().iterator();
            // while(iter.hasNext()){
            // Map.Entry entry = (Map.Entry)iter.next();
            // }
        } catch (ParseException pe) {
            System.out.println(pe);
        }
        return null;
    }

FirefoxDriver Profile in Selenium

1. if the profile isn't already registered with Firefox:
File profileDir = new File("path/to/top/level/of/profile");
FirefoxProfile profile = new FirefoxProfile(profileDir);
profile.addAdditionalPreferences(extraPrefs);
WebDriver driver = new FirefoxDriver(profile);

2. FirefoxDriver inform error when getText(), change to following
WebElement oElem.getAttribute("attribute_name").toString();