Showing posts with label stand alone application. Show all posts
Showing posts with label stand alone application. Show all posts

Saturday, August 08, 2009

String versus StringBuffer



Generally, we use the String and StringBuffer classes for manipulating the character data. Both, String and StringBuffer are available in "java.lang" package.


String class is used to represent the character strings that cannot be changed. In other words, String type objects are read-only and immutable. StringBuffer objects represent the character strings that can be changed.

The other difference between the two is the performance. StringBuffer is much faster than that of String class when performing concatenations. Following lines of code is used to perform the concatenation.

String:
String string = new String("Java ");
string += "Language";

As String class is immutable, the initial string is first converted into StringBuffer and append the second string, then converts it back to String object using the toString() method.

StringBUffer: String buffer class has an "append()" method to concatenate the string data.
StringBuffer strBuf = new StringBuffer("Java ");
strBuf.append("Language");

First method - created three objects. initial String object, temporary StringBuffer and String object to hold the converted StringBuffer data.

Second method - everything is done with just one object creation, i.e. StringBuffer, and appends the data to the StringBuffer.

Overall, Using the StringBuffer there is no need of conversion from String->StringBuffer, and converting back to String, which is an expensive operation. So StringBuffer is a best option for developers to choose when they want to manipulate the character string data.

ArrayList vs Vector

Internally, Vector and ArrayList holds their contents using an array. From API point of view, vector and arraylist are very similar. Vectors are synchronized, where as ArrayList are not. Sometimes its better to use Vector, sometimes its better to user ArrayList. Your choice depends upon the needs. Following are the similarities and differences between the two.

Similarities between ArrayLists and Vectors

  • Both can grow up during run time.
  • Both implement List interface.
  • With both, it is easier to remove or add elements at the end or start, but if you try to add or remove elements somewhere at middle of collection, they suffer performance wise. (Use LinkedLists if your programme need to do that a lot, but LinkList requires more memory and computation)

Differences between ArrayLists and Vectors

  • The major difference is just that vectors are synchronized. This means that if more than one thread in your code is to use that data, you are in trouble with ArrayList as the data is asynchronous. Though there are ways by which you can make your ArrayLists synchronous, but by default they are not. The obvious downside with vectors is the additional computation to handle threads.
  • Vector contains many legacy methods that are not part of collection framework. With Java2 release, Vector reengineered to extend the class AbstractList and implements List interface, now it is fully compatible with collections framework.
  • The other difference is that with vectors, you can specify the incremental value, which is the amount with which the data structure will grow during the runtime. But with ArrayLists you have no option but to accept default that is the list will grow up 50% of original size everytime it needs additional space. It is advisable in both the cases to choose the initial size carefully.

Thursday, August 06, 2009

Converting an Array to a Set

To my knowledge we do not have any direct methods to convert from an array to a set. this To achieve this, we have to do the conversion process in two steps.
1. Converting an array to List
2. Converting the resulting List to a Set

Following program constructs an array with strings, String array is converted into a List using the asList method available in Arrays. Then the resulting list is converted into a Set.

---
package com.blog.javaexposure.util;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Array2Set {
public static void main(String rags[]){
// Creating a string array
String[] str = {"One","Two","Three","Four","
Five"};

// Convert array to List
List list = Arrays.asList(str);

System.out.println("Elements in the list are:");
//Checking the elements in the list
for(String s : list){
System.out.println(s);
}

// Convert list to set
Set set = new HashSet(list);

System.out.println("Elements in the set are:");
//Checking the elements in the set
for(String s : set){
System.out.println(s);
}
}
}

Converting an Array to a List

Java Collections API has very useful methods to play with all the data structures. Conversion between the collections made so easy.

following line of code converts an array into a list.
List list = Arrays.asList(str); // str is an array

Following program converts an array of strings into a List.

package com.blog.javaexposure.util;

import java.util.Arrays;
import java.util.List;

public class Array2List {

public static void main(String rags[]){
// Creating a string array
String[] str = {"One","Two","Three","Four","Five"};

// Convert array to List
List list = Arrays.asList(str);

System.out.println("Elements in the list are:");
//Checking the elements in the list
for(String s : list){
System.out.println(s);
}
}
}

Tuesday, August 04, 2009

How do I convert Set into List?

Conversion between the collections made pretty easy in Java.

Converting from a Set/List to List/Set can be done by passing the Set/List instance to the constructor of List/Set such as ArrayList/HashSet respectively.

Following line of code performs the conversion (from Set to List):

Set strSet = new HashSet();
strSet.add("one")
.
.
.
strSet.add("xxx");

List strList = new ArrayList(set);

Above List can be converted back to Set using the following line of code:

Set setObject = new HashSetst(strList);

Following is the example program that does the entire same thing we discussed above:
-----
package com.blog.javaexposure.util;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Set2List {

public static void main(String rags[]) {
// Creating a Set object
Set set = new HashSet();
// Adding elements to the Set object
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");

// Checking the elements in the Set
System.out.println("Elements in the set are:");
for (Object obj : set) {
System.out.println(obj);
}

// Creating a list object
List list = new ArrayList(set);

// Checking the elements in the list
System.out.println("Elements in the list are:");
for (Object obj : list) {
System.out.println(obj);
}
// Removing elements from the set
set.clear();
System.out.println("Number of elements in the set are: "+set.size());

// Converting list to set
set = new HashSet(list);

// Checking the elements in the Set
System.out.println("Elements in the set are:");
for (Object obj : set) {
System.out.println(obj);
}
}
}
-----

Monday, August 03, 2009

Accessing properties file for efficient read/write










In previous post, we did not use any third party libraries for accessing the properties file. Here, we will be using the apache commons configuration API. You have to download the jar file and add it to the classpath.

Reading from a properties file:

Use the following line of code if you just want to read the properties file.

Configuration config = new PropertiesConfiguration(propertiesFileName);

Then you need to use the various methods available to read the propeties. It has some flexible methods such as to get the string type of values, or integer or a list of values.

Detailed information about Configuration Interface can be found here: org.apache.commons.Configuration

Writing to a properties file:

You have to use the PropertiesConfiguration object to write to the properties file.

Detailed information about PropertiesConfiguration can be found here: org.apache.commons.configuration.PropertiesConfiguration

Use the following code:

PropertiesConfiguration config;
try{
config = new PropertiesConfiguration(propertiesFileName);
config.setProperty(propertyName, propertyValue); //to update properties
config.save(); //writes the changes to the file
}
Catch(ConfigurationException e){
System.out.println("Configuration exception");
}

When you write/update the properties this way,
1. properties order in the file doesn't change
2. comments stays the same

Other Uses: We can save a back up of the properties file using the following method.

config.save(backupFileName). //backupFileName is the name of the back up file to be created

Some useful info from apache website can be found here

Sunday, August 02, 2009

Accessing properties file in a java apps

Properties file is a simple text file. It contains a set of key-value pairs. Each key is associated with a key. We use properties file to store the configuration properties so that we dont need to touch the code again n again and recompile n run the entire app. just editing the properties file should be enough.

I used the following code to load properties from a properties file in J2EE application. Following code shows how to read the properties file and load the available properties into Java.Util.Properties Object.

/* Reading a properties file */

Properties props = new Properties();

//loading the properties from file into "props"
try{
props.load(new FileInputStream(fileName);
//filename should be a string. for ex, abc.properties
}
Catch(IOException e){
System.out.println("IO Exception occurres while accessing the properties file"+fileName);
}

"props" contains all the properties available in the file. i.e. key/value pairs. It simply ignores the comments, if any, available in the file.

Following code shows how to write the properties into a file.
try{
props.store(new FileOutputStream(fileName), null);
}
Catch(IOException e){
System.out.println("IO Exception while accessing the properties file"+fileName);
}

PROS: no use of third party libraries and is easy to read and write from the properties file.
CONS: With this way of reading and writing to the files, all your comments will show at the starting of the file and then shows up the properties. So the comments (if any specific to the property will be gone and all comments mess up at the top of the file)
When to use: I recommend this way to use when your properties file doesn't have any comments. i.e. your properties file just contains key value pairs.

To know more about Java.Util.Properties: Java.Util.Properties

In my next post, I will discuss the efficient way to edit the properties file without affecting the comments and order of the properties.
È