RSS

Category Archives: Java Collections

Some Questions on Collections

1. What is the difference between a List and a Set?
List allows duplicates and maintains the order in which the elements were inserted on the other hand a Set doesn’t allow duplicates and no order is maintained.

2. Tell me some ways to make a synchronized list.
You can use Vector or can use a method provided in Collections class. Collections.SynchronizedList(List list) which returns a synchronized list.

3. What method should the key class of Hashmap override?
The class used as a Key must override equals() and hashCode() methods.

4. What is the key difference between Enumeration and Iterator?
Iterator has a remove() method while Enumeration doesn’t. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, whereas using Iterator we can manipulate the objects also like adding and removing the objects. So Enumeration is used whenever we want to make Collection objects as Read-only.

5. What is the difference between Vector and ArrayList?
Vector is synchronized whereas ArrayList is not.

6. Can a List contain heterogeneous objects?
Yes a List can contain heterogeneous objects. It also depends upon the type declaration of the List. From Java 1.5 onwards use

 List<Object> list = new ArrayList<Object>(); 

to declare a hetrogenous list.

7. How do I sort the Elements in a Collection?
You can use Collections.sort method to sort the elements.

 
1 Comment

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

 

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: , , ,

Difference between HashMap and IdentityHashMap

Most of the time I use HasMap whenever a map kinda object is needed. When reading some blog I came across IdentityHashMap in Java. It is good to understand the differences between the two because you never know when you will see them flying across your code and you trying to find out why is  this kinda Map is used here.

IdentityHashMap as name suggests uses the equality operator(==) for comparing the keys. So when you put any Key Value pair in it the Key Object is compared using == operator.

 import java.util.HashMap;
 import java.util.IdentityHashMap;
 import java.util.Map;

public class IdentityMapDemo {

public static void main(String[] args) {
 Map identityMap = new IdentityHashMap();
 Map hashMap = new HashMap();
 identityMap.put("a", 1);
 identityMap.put(new String("a"), 2);
 identityMap.put("a", 3);

hashMap.put("a", 1);
 hashMap.put(new String("a"), 2);
 hashMap.put("a", 3);

System.out.println("Identity Map KeySet Size :: " +  identityMap.keySet().size());
 System.out.println("Hash Map KeySet Size :: " + hashMap.keySet().size());
 }
 }
 

On the other hand HashMap uses equals method to determine the uniqueness of the Key.

k1.equals(k2)
 

instead of equality operator.

When you run the above code the result will be

Identity Map KeySet Size :: 2
Hash Map KeySet Size :: 1

The Keysize of Identity Map is 2 because here a and new String(“a”) are considered two different Object. The comparison is done using == operator.

For HashMap the keySize is 1 because K1.equals(K2) returns true for all three Keys and hence it keep on removing the old value and updating it with the new one.

These both Maps will behave in same manner if they are used for Keys which are user defined Object and doesn’t overrides equals method.

 
5 Comments

Posted by on March 24, 2010 in Java, Java Collections