Archive for the ‘Java’ Category
Using StringReader to iterate over a String
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);
}
Creating singleton collections
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.
Creating unmodifiable & synchronized collections
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:
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:
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());
Implementing equals(), hashCode(), toString() & compareTo() using reflection
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:
Using CompareToBuilder to implement Comparable interface
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.
