RSS

Tag Archives: Java

Sorting List in Java

Sorting Lists in Java is a common task. For this Java provides Comparators and Comparables. These are Interfaces which are required to be implemented for sorting purpose. For the demonstration we will consider one at a time. sort method of Collections class in used to sort. This method is overloaded one takes List as its parameter and other takes List and Comparator as its arguments.

Sorting using Comparable Interface:

This Interface has a method compareTo. It compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. In the code provided below the Person class implements Comparable Interface.

package com.sample.beans;

import java.util.Date;

/**
 * @author hgupta
 *
 */
public class Person implements Comparable<Person> {

	/** used for name of the Person **/
	private String name;
	
	/** used for home address of the Person **/
	private String address;
	
	/** used for Date of Birth **/
	private Date dateOfBirth;
	
	/** used for phone number **/
	private Integer phoneNumber;

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the address
	 */
	public String getAddress() {
		return address;
	}

	/**
	 * @param address the address to set
	 */
	public void setAddress(String address) {
		this.address = address;
	}

	/**
	 * @return the dateOfBirth
	 */
	public Date getDateOfBirth() {
		return dateOfBirth;
	}

	/**
	 * @param dateOfBirth the dateOfBirth to set
	 */
	public void setDateOfBirth(Date dateOfBirth) {
		this.dateOfBirth = dateOfBirth;
	}

	/**
	 * @return the phoneNumber
	 */
	public Integer getPhoneNumber() {
		return phoneNumber;
	}

	/**
	 * @param phoneNumber the phoneNumber to set
	 */
	public void setPhoneNumber(Integer phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

	@Override
	public int compareTo(Person o) {
		return this.getName().compareTo(o.getName());
	}
	
}

Here the Person class implements the Comparable Interface and so it has the method compareTo. Here in this example it uses String’s compareTo method to compare the String at the base. Depending upon the comparison it returns an int which can be –ve, +ve or 0. Here one concept to be mentioned is it only depends upon the sign of the number but not its magnitude.
Now we will also write a Comparator which will be used to sort the List of Person on the property named dateOfBirth which is of Date type.

package com.comparators;

import java.util.Comparator;

import com.sample.beans.Person;

/**
 * @author Himanshu
 *
 */
public class PersonDOBComparator implements Comparator<Person> {

	@Override
	public int compare(Person o1, Person o2) {
		return o1.getDateOfBirth().compareTo(o2.getDateOfBirth());
	}


}

The PersonDOBComparator implements the Comparator Interface. The method compare takes two arguments and compares them. Using Comparator is easy. If you have any final class whose code cannot be modified, at that stage you can write a comparator. Also if you have a functionality in which you have to sort the List on a number of properties then writing a comparator for each property is easy. Also there are some libraries available which provides comparator on the fly.
Let us sort a List containing Person’s Objects. For this we will make a CollectionSorter.java class which will sort and display the sorted results to the user.

package com.collection.sorting.examples;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;

import com.comparators.PersonDOBComparator;
import com.sample.beans.Person;

/**
 * @author hgupta
 *
 */
public class CollectionSorter {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CollectionSorterUtil collectionSorterUtil = new CollectionSorterUtil();
		ArrayList<Person> persons = collectionSorterUtil.getPersonsAsArrayList();
		System.out.println("Orignal List");
		displayPersons(persons);
		Collections.sort(collectionSorterUtil.getPersonsAsArrayList());//Line 1
		System.out.println("List Sorted By Name");
		displayPersons(persons);
		Collections.sort(collectionSorterUtil.getPersonsAsArrayList(), new PersonDOBComparator());// Line 2
		System.out.println("List Sorted By Date of Birth");
		displayPersons(persons);
	}

	private static void displayPersons(ArrayList<Person> persons){
		DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
		System.out.println("----------------------------------------------------------");
		for(Person person:persons){
			System.out.print(person.getName());
			System.out.println(" " + dateFormat.format(person.getDateOfBirth()));
		}
		System.out.println("----------------------------------------------------------");
	}
}

This class uses another utility class named CollectionSorterUtil.java which populated the list used by CollectionSorter class. At Line 1 we have used Collections.sort(List list) method to sort the List. It uses the method compareTo which we provided in the Person class by implementing Comparable Interface. At Line 2 we have used a Comparator to sort it. This Comparator uses dateOfBirth to sort the List.

package com.collection.sorting.examples;

import java.util.ArrayList;
import java.util.Date;

import com.sample.beans.Person;

/**
 * @author hgupta
 *
 */
public class CollectionSorterUtil {

	/** ArrayList to store Persons Object**/
	ArrayList<Person> persons = new ArrayList<Person>();
	{
		populatePersons();
	}
	
	/**
	 * This method returns a collection of Person
	 * Objects.
	 * @return {@link ArrayList} Person
	 */
	public  ArrayList<Person> getPersonsAsArrayList(){
		return this.persons ;
	}
	
	private void populatePersons(){
		Person person = new Person();
		person.setName("Mark");
		person.setDateOfBirth(new Date("02/12/1987"));
		persons.add(person);
		
		person = new Person();
		person.setName("Anthony");
		person.setDateOfBirth(new Date("02/30/1987"));
		persons.add(person);
		
		person = new Person();
		person.setName("Zulia");
		person.setDateOfBirth(new Date("02/12/1987"));
		persons.add(person);
		
		person = new Person();
		person.setName("Jenifer");
		person.setDateOfBirth(new Date("05/2/1988"));
		persons.add(person);
		
		person = new Person();
		person.setName("Jhon");
		person.setDateOfBirth(new Date("01/11/1987"));
		persons.add(person);
		
		person = new Person();
		person.setName("Russels");
		person.setDateOfBirth(new Date("02/12/1980"));
		persons.add(person);
		
		person = new Person();
		person.setName("Erik");
		person.setDateOfBirth(new Date("05/25/1984"));
		persons.add(person);
		
		person = new Person();
		person.setName("Peter");
		person.setDateOfBirth(new Date("12/02/1997"));
		persons.add(person);
		
	}
	
}

After you run the CollectionSorter class you will see the following output in the console.

Orignal List
----------------------------------------------------------
Mark 02/12/1987
Anthony 03/02/1987
Zulia 02/12/1987
Jenifer 05/02/1988
Jhon 01/11/1987
Russels 02/12/1980
Erik 05/25/1984
Peter 12/02/1997
----------------------------------------------------------
List Sorted By Name
----------------------------------------------------------
Anthony 03/02/1987
Erik 05/25/1984
Jenifer 05/02/1988
Jhon 01/11/1987
Mark 02/12/1987
Peter 12/02/1997
Russels 02/12/1980
Zulia 02/12/1987
----------------------------------------------------------
List Sorted By Date of Birth
----------------------------------------------------------
Russels 02/12/1980
Erik 05/25/1984
Jhon 01/11/1987
Mark 02/12/1987
Zulia 02/12/1987
Anthony 03/02/1987
Jenifer 05/02/1988
Peter 12/02/1997
----------------------------------------------------------

 
Leave a comment

Posted by on September 10, 2010 in Java, Java Collections

 

Tags: , , ,

Installing Tomcat on Windows

Tomcat is an open source servlet and JSP container. It is very easy to install and use. Many Java developers around the world use it. It has got very strong community support and has evolved a lot.  This article gives stress on the installation process of tomcat. To install Tomcat follow the step given as under:

  1. Download the Tomcat from the URL: http://tomcat.apache.org/download-60.cgi . There are two types of files available to download. One is to download the zip file and extract it. Second one is .exe windows installer file to install it in your PC. Second approach is much easier and it will install the service also to start and stop the tomcat server.
  2. If you have downloaded the .exe file just run it by double clicking it and it will install tomcat on your PC. In case you have downloaded the Core version of it then unzip the file to a folder. After unzipping it you will see the following directories inside parent tomcat directory.
  3. tomcat home directory

  4. Deploying a web-application: If you want to deploy any web application put it in the directory named webapp. The application should be a valid web application so that it can be deployed successfully.
  5. Starting /Stopping the Server: Go to the bin directory and double click the startup.bat file to start the server. You will see some logs in the console which opens up when you click the startup file. To shut it down click the shutdown.bat.

Tomcat bin Directory

Tomcat Startup screen

The Console window will show you the log messages when it starts and stops. If you don’t want to stop the server by clicking shutdown.exe you can press CTRL+C in the console window. It will stop the server by itself.

 
Leave a comment

Posted by on September 10, 2010 in Java, Servers

 

Tags: , ,

What are Servlets?

As seen from the top then Servlets are no different as compared to a Java class. They provide a component based way to design a web application. Using servlets web developers can create fast and efficient server side application which can run on any servlet enabled web server. Servlets run entirely inside the Java Virtual Machine and so have access to the whole set of Java API. Also an application written using Servlets can be deployed in any container and it will work. Servlets are popular choice for building interactive Web applications. Third-party servlet containers are available for example Apache Web Server, Microsoft IIS, and others. Servlet containers are usually a component of Web and application servers, such as BEA WebLogic Application Server, IBM WebSphere, Sun Java System Web Server, Sun Java System Application Server, and others.

Servlets are not bound to any specific protocol and can be extended to design one of its own choice but commonly servlets designed to work with HTTP(Hyper Text Transfer Protocol) are used heavily. These Servlets are controlled by the container from their creation to collection by Garbage Collector.

 
Leave a comment

Posted by on July 7, 2010 in J2EE, Java

 

Tags: ,

Spring Dependency Injection

Spring DI is the most fundamental feature that it provides. This feature has also been referred as Inversion of Control but after many discussions it was decided that DI is a better term.

Any application which is of practical use is composed of two or more Objects which communicate or use each other.  Traditionally each of those objects is responsible to get the reference of objects it uses but in DI objects are given references to the other objects when needed. All the bean creation and their injection are handled by Spring which acts as a container of beans. This provides loose coupling and also promotes programming to an Interface as the bean knows only about the type of bean but nothing about its implementation.

For Example: If the bean Store has declared Product property as an interface then the Product implementation becomes irrelevant.   The Product bean can be web-service implementation, an EJB or a mock test object.

Some other benefits of using DI:
• Reduction of boiler plate coding.
• As all metadata is in xml file and is easy to configure. This gives flexibility in testing and development.

 
Leave a comment

Posted by on July 5, 2010 in Java, Spring

 

Tags: ,

Java Example of Spring Dependency Injection

This tutorial uses the following:

    • Eclipse IDE
    • Spring Jars
    • commons-logging-api-1.1.jar
  1. Make a new Java Project in Eclipse.
  2. Add the following jars to its classpath:
    • commons-logging-api-1.1.jar
    • org.springframework.core-3.0.2.jar
    • org.springframework.beans-3.0.2.jar

The Spring jars can be taken from the dist folder of the expanded zip file. Here you have to include the two jars one for core and other for beans. Commons-logging is used for logging purpose.

  • Make a new class – Person.java. It is a 100% Java bean and has the proper getters and setters.
package com.spring.ioc.beans;

public class Person {

	private String name;

	private String address;

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the address
	 */
	public String getAddress() {
		return address;
	}

	/**
	 * @param address the address to set
	 */
	public void setAddress(String address) {
		this.address = address;
	}

}

  • Make an XML file and name it context.xml and save it in the src folder.  This file contains all the meta information needed for bean creation. Here the bean id is person and class has the full qualified name of the class. The “name” property of the class Person is populated with the value Mac.

<?xml version="1.0" encoding="UTF-8"?>
xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
	<bean id="person" class="com.spring.ioc.beans.Person">
	<property name="name" value="Mac"></property>
	</bean>
</beans>

  • Make another class named Main.java.  Here an object of XmlBeanFactory loads the configurations from contect.xml file. Also its constructor takes an argument of ClassPathResource.
  • To get a bean from XmlBeanFactory object use its reference type to invoke the method getBean(<bean id>) and it will return the bean as defined in the spring context file.  The Object it returns is of type Object so you do have to cast it to the correct type.
package com.spring.ioc.main;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

import com.spring.ioc.beans.Person;

/**
 * @author hgupta
 *
 */
public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
				"context.xml"));
		Person person = (Person) beanFactory.getBean("person");
		System.out.println(person.getName());
	}

}

  • Run the Main class as Java Application and you will see the following output: The output is the name of the person which you configured in the xml file.

Output:

May 27, 2010 6:54:04 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

INFO: Loading XML bean definitions from class path resource [context.xml]

Mac

 
Leave a comment

Posted by on July 5, 2010 in Java, Spring

 

Tags: ,

Spring Framework Architecture

Spring framework is layered in architecture which consist several modules. All its modules are built on the top of its core container. These modules provide everything that a developer may use in the enterprise application development. He is always free to choose what all features he needs and eliminate the modules which are of no use. Its modular architecture enables integration with other frameworks without much hassle.


The Core Module: It provides the Dependency Injection (DI) feature which is the basic concept of spring framework. This module contains the BeanFactory an implementation of Factory Pattern which creates the bean as per the configurations provided by the developer in an XML file.

AOP Module: Its Aspect Oriented Programming module allows developer to define method-interceptors and point cuts to keep the concerns apart. It is configured at run time so the compilation step is skipped. It aims at declarative transaction management which are easier to maintain.

DAO Module: This provides an abstraction layer to the low level task of creating a connection, releasing it etc. It also maintains a hierarchy of meaningful exception rather than throwing complicated error codes of specific database vendors. It uses AOP to manage transactions. Transactions can also be managed programmatically.

ORM Module: Spring doesn’t provides its own ORM implementation but offers integrations with popular Object Relational mapping tools like Hibernate, iBATIS SQL Maps, Oracle TopLink and JPA etc.

JEE Module: It also provides support for JMX, JCA, EJB and JMS etc. In lots of cases, JCA (Java EE Connection API) is much like JDBC, except where JDBC is focused on database JCA focus on connecting to legacy systems.

Web Module: Spring comes with MVC framework which eases the task of developing web applications. It also integrates well with the most popular MVC frameworks like Struts, Tapestry, JSF, Wicket etc.

 
Leave a comment

Posted by on July 5, 2010 in Java, Spring

 

Tags: , ,

Java Strings

Whenever we make a String object by doing some operation on the Strings then we will always end up with new String Object.

String class has overridden hashCode() and equals() method so meaningfully the String objects may be equal and they will return the same hash code but then also they are situated at different memory location in the Objcet heap.

The default implementation of hashCode() provided by Object is derived by mapping the memory address of the object to an integer value. Because on some architectures the address space is larger than the range of values for int, it is possible that two distinct objects could have the same hashCode(). If you override hashCode(), you can still use the System.identityHashCode() method to access this default value.
src

The following example will simplify my point.


public class MWC109 {
public static void main(String args[]) {
String a = "A", b = "B", c = a+b, d = a+b;
System.out.println("a+b hashcode: " + (a+b).hashCode());
System.out.println("c hashcode: " +  c.hashCode() );
System.out.println("d hashcode: " + d.hashCode());
System.out.println();
System.out.println("c system hash code: " + System.identityHashCode(c) );
System.out.println("d system hash code: " + System.identityHashCode(d) );
System.out.println();
for (int i =0; i<10; i++){
System.out.println(i + ") a+b System HashCode: " + System.identityHashCode((a+b)));
}
System.out.println();
String str1 = "POps";
String str2 = "POps";
System.out.println("str1 System HashCode: " +  System.identityHashCode(str1));
System.out.println("str2 System HashCode: " + System.identityHashCode(str2));
System.out.println("str1 hashcode: " + str1.hashCode());
System.out.println("str2 hashcode: " + str2.hashCode());
System.out.println();
for (int i=0; i<10; i++){
System.out.println(i + ") str1+str2 System HashCode: " + System.identityHashCode(str1+str2));
}
System.out.println();
System.out.print(((a+b)==(a+b)) + ",");
System.out.print((c==d) + ",");
System.out.println(c.equals(d));
}}

The output of the above code is


a+b hashcode: 2081
c hashcode: 2081
d hashcode: 2081
c system hash code: 4072869
d system hash code: 1671711
0) a+b System HashCode: 11394033
1) a+b System HashCode: 4384790
2) a+b System HashCode: 9634993
3) a+b System HashCode: 1641745
4) a+b System HashCode: 11077203
5) a+b System HashCode: 14576877
6) a+b System HashCode: 12677476
7) a+b System HashCode: 33263331
8) a+b System HashCode: 6413875
9) a+b System HashCode: 21174459
str1 System HashCode: 827574
str2 System HashCode: 827574
str1 hashcode: 2462786
str2 hashcode: 2462786
0) str1+str2 System HashCode: 17510567
1) str1+str2 System HashCode: 27744459
2) str1+str2 System HashCode: 28737396
3) str1+str2 System HashCode: 6927154
4) str1+str2 System HashCode: 24355087
5) str1+str2 System HashCode: 5442986
6) str1+str2 System HashCode: 10891203
7) str1+str2 System HashCode: 9023134
8) str1+str2 System HashCode: 19336051
9) str1+str2 System HashCode: 6336176
false,false,true

So it is visible that whenever we make some String object by doing some alteration we will always end up in a new Object in heap. So the system HashCode will be different for them as no two Objects can share the same memory.

The hashcodes we get from the String Objects return the hashcode generated by this function as it is overridden in String class.


public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}

To get the actaul hashcode we used the static function identityHashCode() of System class.
The system hashcode for str1 and str2 are same as those objects were created without any alteration on any of the objects.v

 
1 Comment

Posted by on June 12, 2009 in Java

 

Tags: