Parambir.in

Things I Came Across…

Archive for the ‘Java’ Category

Using StringReader to iterate over a String

without comments

StringReader makes it quite convenient to iterate over a string character by character as follows:

StringReader reader = new StringReader("This is a string.");
int ch;
while((ch = reader.read()) != -1)
{
System.out.println((char)ch);
}

Written by Param

March 12th, 2010 at 3:27 pm

Posted in Java

Tagged with

Creating singleton collections

without comments

The Collections class in the java.util package provides convenient methods to create singleton collection objects. A singleton collection object is a List, Map or Set that contains only a single element. Here’s how you can create a singleton set:

Set set = Collections.singleton( "The Element" );

There are 2 more methods which allow you to create a singleton list or map:

List list = Collections.singletonList( "The Element" );
Map map = Collections.singletonMap( "Key" , "Value" );

The collection object returned in all these methods is an immutable object. Also, all 3 of them are static methods in the Collections class.

Written by Param

March 4th, 2010 at 10:37 am

Posted in Java

Tagged with , , , ,

Creating unmodifiable & synchronized collections

without comments

By default, the classes available in the Java Collections framework are read/write enabled & not thread safe. Sometimes the requirement is to have read only i.e. unmodifiable collections. The Collections class available in the java.util package provides utility methods to create such collections. Note: Do not confuse this class with the Collection interface which is the root interface of the collection hierarchy.

The objects returned by these methods are wrappers over the original collection object you supply to the method (Decorator design pattern).

The Collections class has 6 static methods that return a read only collection object. These are:

  • static Collection unmodifiableCollection(Collection c)
  • static List unmodifiableList(List list)
  • static Map unmodifiableMap(Map m)
  • static Set unmodifiableSet(Set s)
  • static SortedMap unmodifiableSortedMap(SortedMap m)
  • static SortedSet unmodifiableSortedSet(SortedSet s)


It is important that you don’t store the reference to the original object, otherwise you’ll still be able to access the original object and thus the collection will not be unmodifiable. Therefore, it is best to first populate the collection with the desired values and then replace the original reference with the read-only reference e.g.

List list = new Arraylist();
// populate the list
list = Collections.unmodifiableList(list);

The classes available in the collections package are not thread safe by default. The designers of the Java collections hierarchy did this on purpose since synchronized collection classes are slower and you don’t require synchronization always. The Collections class has 6 utility static methods to wrap collection objects into synchronized ones. These methods are:

  • static Collection synchronizedCollection(Collection collection)
  • static List synchronizedList(List list)
  • static Map synchronizedMap(Map map)
  • static Set synchronizedSet(Set set)
  • static SortedMap synchronizedSortedMap(SortedMap map)
  • static SortedSet synchronizedSortedSet(SortedSet set)


It is best to create a collection object and then wrap it in a synchronized one immediately. Also, you should not keep the reference to the original object otherwise you’ll be able to access it in a thread-unsafe manner. The best way to do this is to create a synchronized collection object as follows:

List list = Collections.synchronizedList(new ArrayList());

Written by Param

March 2nd, 2010 at 2:20 pm

Implementing equals(), hashCode(), toString() & compareTo() using reflection

without comments

In my previous posts, I wrote about the various utility classes provided by Apache’s commons lang library for implementing commonly used methods (equals(), hashCode() etc.). All of these classes also provide the option of implementing these methods using reflection. That reduces your code for implementing any of these methods to just writing one line! For example, to implement toString() method using reflection, use the reflectionToString() static method of the ToStringBuilder class. Here’s the implementation of all the above methods using reflection in a sample class:

public class Account implements Comparable
{
private long id;
private String firstName;
private String lastName;
private String emailAddress;
private Date creationDate;

public boolean equals(Object obj)
{
return EqualsBuilder.reflectionEquals(this, obj);
}

public int hashCode()
{
return HashCodeBuilder.reflectionHashCode(this);
}

public int compareTo(Account account)
{
return CompareToBuilder.reflectionCompare(this, account);
}

public String toString()
{
return ToStringBuilder.reflectionToString(this);
}

However, these methods use AccessibleObject.setAccessible() method to change the visibility of class fields (since generally these fields are private). This will not work under a security manager, unless appropriate permissions are set up correctly. Also, these methods are slower than testing explicitly.

References:

Written by Param

March 1st, 2010 at 12:20 pm

Using CompareToBuilder to implement Comparable interface

without comments

Many a times, we need to implement the java.lang.Comparable interface. This interface has a single method int compareTo(Object o). Apache’s Commons Lang library provides a utility class – CompareToBuilder which makes it easy to write the compareTo() method. The method is consistent with with equals() and hashCode() methods built using EqualsBuilder and HashCodeBuilder (provided the same fields are used in all of them). A typical use of the class is as follows:

public class Account implements Comparable<Account>
{
  private long id;
  private String firstName;
  private String lastName;
  private String emailAddress;
  private Date creationDate;

public int compareTo(Account account)
  {
   return new CompareToBuilder().append(this.id, account.id)
    .append(this.firstName, account.firstName)
    .append(this.lastName, account.lastName)
    .append(this.emailAddress, account.emailAddress)
    .append(this.creationDate, account.creationDate)
    .toComparison();
  }
}

We first create an instance of the CompareToBuilder. The append method takes two arguments – the two fields we want to compare. It returns an instance of CompareToBuilder so multiple calls to the append method can be chained (as in the above example). Finally we call the toComparison() method which returns the appropriate value to the caller.

References:

Written by Param

February 27th, 2010 at 11:31 am

Posted in Java

Tagged with , , ,