Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Monday, August 31, 2009

Solutions to Two More Java Puzzlers

In my last post, Two More Java Puzzlers, I gave two puzzling snippets of Java code that don't act exactly as expected.

The first puzzle asked why the following code prints null instead of either "even" or "odd" as expected.

public static void main(String[] args)
{
String a = null;
int n = "number".hashCode();

switch( n % 2 ) {
case 0:
a = "even";
break;
case 1:
a = "odd";
break;
}

System.out.println( a );
}

This code uses n % 2 as the condition on a switch with cases for 0 and 1. Strangely, neither of the cases is executed. What other return values could the modulo operator produce when the divisor is 2? Surely 0 and 1 are the only two possible remainders when dividing by 2, aren't they?

Usually that's the case. "Usually" meaning, "for positive dividends." The Java % operator doesn't return the modulus in a strict mathematical sense. What it returns is the remainder.

What's the difference? In this particular case "number".hashCode() returns a negative value. When n is negative in the operation n % 2, the result will be negative too.

This isn't just a problem in Java. Some languages specify that the % operator is a strict modulus function, and some specify that it returns the remainder. You should know how the operator reacts to negative inputs in whatever language you're using.

To fix the code above, just use the absolute value of the result of the remainder operation.

The second puzzle asked why the following code crashes where it does, and why doesn't it crash sooner?

public static void main(String[] args)
{
Vector<Integer> numbers = new Vector<Integer>();

int min = 128;
int max = 255;

for( int i = min; i <= max; ++i )
{
numbers.add(i);
}

int element = 100;

numbers.remove(element);

element = 255;

if( numbers.contains(element) )
{
numbers.remove(element);
}
}

The code above creates a Vector of Integer objects, then adds the values from 128 to 255 to the Vector. It then removes element 100, checks to see if the Vector contains and element with the value 255, and attempts to remove it if it does. (At least this is what it appears to be doing.)

If you run the code above you will see it crash on line 21, when the second remove operation is attempted. Why does it crash there and not the first time it attempts to removes an element? The second element removed has a value of 255, which was added to the Vector. If that value wasn't found in the Vector, the remove operation wouldn't even execute. It should crash earlier, when the attempt to remove the element with the value of 100 is executed, if it's going to crash at all, shouldn't it? There is no element with that value to remove.

The problem with the above code is related to auto-boxing. More precisely, it's a lack of auto-boxing at the critical point that's causing the code to fail. Note that on line 10 when the int values are added to the Vector, they're automatically wrapped and added as Integer objects. This might lead you to believe that the same thing will happen when you try to remove elements from a Vector, as well. This isn't the case when the elements are Integers, though.

The problem is that Vector has a remove(int index) method that interferes with the auto-boxing that would normally occur when you try to remove an int. The statement on line 21 above is attempting to remove the element at index 255, which doesn't exist, instead of the element with the value 255, which does. The contains method isn't overloaded, so the condition on line 19 evaluates to true, allowing the fatal line of code to execute.

And what about the other remove operation? It has the same problem, only reversed. It appeared to be attempting to remove the element with the value of 100, which doesn't exist, but it was really removing the element at index 100, which does exist. This could be a particularly insidious bug if the values never go out of range. Instead of crashing quickly and alerting you to a problem, it could just quietly remove the wrong values.

To fix the bugs in this puzzler, just wrap the variable element in an Integer object before using it as an argument to remove, to make sure the expected method is called. And what lessons can we learn? Never assume. Always check to make sure you know exactly which operations will use auto-boxing, and which operations won't, with whatever libraries you use.

Saturday, August 29, 2009

Two More Java Puzzlers

Oh, Java! Will you ever run out of corner cases to confuse and bewilder me? I doubt it. On the bright side, you are an unquenchable fountain of fun programming puzzles for my blog. Thanks, Java!

Odd or Even?

Today's first puzzler comes to us courtesy of @royvanrijn. Take a look at the following code:

public static void main(String[] args)
{
String a = null;
int n = "number".hashCode();

switch( n % 2 ) {
case 0:
a = "even";
break;
case 1:
a = "odd";
break;
}

System.out.println( a );
}

At first glance it looks like this program should print either "even" or "odd", but looks can be deceiving. The program prints null. The question is, why?


Who uses Vector anyway?

Our second puzzler comes from my boss, Chris. It's a very contrived variation of a problem that he encountered in a very real project. The following code crashes at a point you might not expect. Can you tell why it crashes there, and why it didn't crash before that point?

public static void main(String[] args)
{
Vector<Integer> numbers = new Vector<Integer>();

int min = 128;
int max = 255;

for( int i = min; i <= max; ++i )
{
numbers.add(i);
}

int element = 100;

numbers.remove(element);

element = 255;

if( numbers.contains(element) )
{
numbers.remove(element);
}
}

A co-worker figured this one out in under a minute after he was told that it wasn't a threading issue (which should be obvious from this contrived example, but wasn't in the original context). See if you can beat his very impressive time.

I'll have the answers to both puzzlers in an upcoming post.



As always, I can't bring up the subject of Java puzzlers without mentioning the book Java Puzzlers: Traps, Pitfalls, and Corner Cases by Josh Bloch and Neal Gafter. It's a collection of 95 Java puzzles plumbed from the depths of the language and its core libraries.

Monday, July 27, 2009

The Broken Stick Experiment

I found several interesting video lectures at the BLOSSOMS Video Library. One in particular that I enjoyed is called The Broken Stick Experiment [Flash]. In it, Professor Richard Larson asks the seemingly simple question,
If you break a stick randomly in two places, what is the probability that you can form a triangle from the three pieces?
If one of the pieces is too long, then the other two can't meet to form the triangle.
The lecture is only 33 minutes, and Professor Larson builds up a very pretty geometric proof, so I won't spoil it by posting the answer here. I will provide code for a simulation, though (yes, this is still a programming blog). See if you can guess the answer before running the simulation or watching the video.

import java.util.Arrays;
import java.util.Random;

public class BrokenStick {

public static void main(String[] args) {
Random random = new Random();

int trials = 10000;
int triangles = 0;

double[] breaks = new double[2];
double[] sides = new double[3];

for( int i=0; i < trials; ++i )
{
breaks[0] = random.nextDouble();
breaks[1] = random.nextDouble();
Arrays.sort(breaks);

sides[0] = breaks[0];
sides[1] = breaks[1] - breaks[0];
sides[2] = 1.0 - breaks[1];
Arrays.sort(sides);

if( sides[2] < (sides[0] + sides[1]) )
{
triangles++;
}
}

System.out.println("Triangles: " + triangles);
System.out.println("Trials: " + trials);

double p = (double)triangles / trials;
System.out.println("Proportion: " + p);
}
}


The simulation breaks 10,000 sticks each into three random pieces using Java's Random class to come up with random lengths. If the longest piece of broken stick is longer than the two remaining pieces, a triangle can't be formed. Ten-thousand trials should be enough to accurately estimate the proportion of triangles made from the broken sticks to two decimal places. How close was your guess?

Related:
The Broken Stick Revisited

Monday, June 8, 2009

A Java Puzzler

A co-worker presented me with the following Java puzzle today (thanks, Josh). Given the following two classes:

public class Base
{
Base() {
preProcess();
}

void preProcess() {}
}

public class Derived extends Base
{
public String whenAmISet = "set when declared";

@Override void preProcess()
{
whenAmISet = "set in preProcess()";
}
}

what do you think the value of whenAmISet will be when a new Derived object is created?

public class Main
{
public static void main(String[] args)
{
Derived d = new Derived();
System.out.println( d.whenAmISet );
}
}

Give yourself a few minutes to look it over before reading ahead. It's a really simple example to follow, so no fair compiling and running it to find out. Think you know the answer?

It appeared to most people that the output should be "set in preProcess()". The reasoning went that when the Derived constructor is called, it implicitly calls the Base constructor via a call to super() that the constructor inserts automatically for you. The Base constructor then makes a call to the most specific copy of preProcess() that it can find, the one in the partially constructed Derived class, which sets the value of the whenAmISet member variable.

This, of course, is wrong. If you compiled and ran the code above you found that it prints out "set when declared". So what happened there? Is the Base class preProcess() method getting called? Nope. (Go ahead and put a print statement in each preProcess() method if you don't believe me.)

Here's the sequence of events:
  1. The Derived constructor is called.
  2. Memory for Derived member variables is allocated.
  3. The Base constructor is called implicitly.
  4. The Base constructor calls preProcess().
  5. preProcess sets whenAmISet value to "set in preProcess()".
  6. Derived class member initializers are called.
  7. The body of the Derived class constructor is called.
Wait, what just happened? At step 6, the Derived class members are initialized after the call to the preProcess() method? That's right. You can't count on the declaration and initialization of member variables being atomic. As you can see from running the example, the initialization of whenAmISet in Declared is over-writing the value that gets set earlier in the preProcess() method.

How do we know this is the right sequence? Let's take a closer look at the significant steps.
  1. We call the constructor.
  2. We know the memory for Derived class member variables is allocated before any line of code is run in its constructor. If this weren't the case then the call to preProcess() in the Base class wouldn't be able to set the value of whenAmISet and print it's value (which isn't in the code above, but you can try it and see that this works).
  3. Java inserts a call to super() at the beginning of the constructor unless you include it yourself.
  4. We know this by looking at the code.
  5. Also known by code inspection.
  6. The initialization must be happening after the call to preProcess(). The Derived class's preProcess() method is getting called, and it is setting whenAmISet's value to "set in preProcess()". Again, if you don't believe me, print out the value of whenAmISet right after it gets set in the Derived preProcess() method.
  7. We're calling the default (empty) constructor, so there's nothing more to see here.
You can see the relevant section of the Java Language Specification for a much more detailed explanation of the process of object creation in Java. (Thanks to Weeble for providing this link in the comments.) Note that there's a very similar example to this one on that page if you scroll down to the paragraph starting "Unlike C++..."

So what can we take away from all of this? First, never count on any operation being atomic unless you've tested and proven it to be so (and sometimes not even then). Second, and more to the point, be careful initializing member variables in a method of a derived class if that method gets called by the base class constructor. It might be even better to try and avoid calling methods in your base constructors that are overridden by derived classes, and conversely, avoid overriding methods in derived classes that are called by the constructor in the base class. Be careful if you do, and don't say I didn't warn you about what might happen.


Further Reading

I could hardly finish without mentioning that Joshua Bloch and Neal Gafter wrote an entire book full of similar puzzles called Java Puzzlers: Traps, Pitfalls, and Corner Cases. Check it out if you'd like being your team's source for Java trivia and minutae.

Saturday, May 30, 2009

How do you test a random number generator?

Human beings are notoriously bad at generating random numbers and sequences. If you ask someone to randomly choose a number between 1 and 20, the numbers they're most likely to choose are 7 and 17. Similarly, if you ask someone to simulate a series of coin flips by writing down a random string of the letters H and T, you'll see very few long sequences of either heads or tails, which would occasionally appear by chance in sequences of real coin flips.

People are just as bad a determining whether an existing sequence is random. Look closely at the following two images.
Original image courtesy of Peter Coles.Original image courtesy of Peter Coles.

Which one do you think looks more randomly distributed? If you read the article that the images link to, you already know that most people say the first image looks more random because the points are more smoothly distributed. This is exactly the property that makes it less random than the second image, which has more instances of points in tight clusters. A real set of random data points wouldn't be as evenly spaced as the first image.

Computers are much better than people, but by no means perfect, at generating sequences of random numbers. A number or sequence is said to be random if it is generated by a non-deterministic and unpredictable process. Since computers are inherently deterministic machines, this means that no computer can ever algorithmically generate a sequence that is truly random. They can come very close, though, with the help of a class of algorithms known as pseudo-random number generators (PRNG).

For a programmer writing a PRNG, or software that relies on one, testing its randomness reveals a unique problem. Unit testing software compares the output of a function to an expected value. If the output is expected to be unpredictable, you have a testing dilemma.

To make matters worse, there is no way even theoretically to prove that a sequence was generated randomly. Luckily there are statistical methods that are useful for revealing when a sequence is not random. Let's take a look at a simple PRNG, then use a common statistical method, the Monte Carlo method, to compare its effectiveness to a standard software library implementation.

A Naive PRNG

One of the oldest algorithmic methods for generating pseudorandom numbers is called the linear congruential method. Here's a simple example implementation:


public class NaiveRandom {
private int x; // seed

private int m = 134456; // modulus
private int a = 8121; // multiplier
private int c = 28411; // increment

public NaiveRandom()
{
x = 0;
}

public NaiveRandom(int seed)
{
this.x = seed;
}

public double next()
{
x = (x * a + c) % m;
return x / (double)m;
}
}

The original pseudocode and constants in the code above come from an example given in Statistical Mechanics by Werner Krauth. As Krauth explains in his book, these values are good for studying the algorithm, but not great if you need really random values. In the following section we'll see how it compares to Java's built-in PRNG.

The Monte Carlo Pi Program

Take a unit circle inscribed in a square.


The area of a circle is given by the formula

A = πr2

Since the radius is 1, the area is equal to π. Since the diameter of the circle and the length of a side of the square are both 2, the area of the square is 4. The ratio (which we'll call ρ) of the area of the circle to the area of the square is

ρ = π / 4 = 0.785398164

If we select a random sample of points from the square, the proportion of those points lying inside the circle should be equal to ρ. We can multiply this proportion by 4 for comparison to a library value of π. If the random number generator is close to truly random, then the closer our approximation should be to the actual value of π.

We can simplify the calculations necessary for the test if we only concern ourselves with one quadrant of the square. This is possible because it's the proportion of points inside the circle to those inside the square that matters. The proportion of such points is the same in each quadrant as it is in the whole. If we say that the center of the circle is at point (0, 0), then we need only generate random points (x, y) where x and y are both between 0.0 and 1.0. This is the standard output range for most PRNGs, like Java's Random class. Points that lie within the circle will be those that obey the inequality

x2 + y2 ≤ 1

Here is the Java code for a Monte Carlo Pi simulation.


import java.util.Date;
import java.util.Random;

public class MonteCarloPi {

public static void main(String[] args) {
// seed for NaiveRandom
Date now = new Date();
int seconds = (int)now.getTime();

// create random number generators
NaiveRandom nrand = new NaiveRandom(seconds);
Random rand = new Random();

// total number of sample points to take
int numPoints = 10000;

int inNaiveCircle = 0;
double xn, yn, zn;
// xn and yn will be the random point
// zn will be the calculated distance to the center

int inRandCircle = 0;
double xr, yr, zr;
// xr and yr will be the random point
// zr will be the calculated distance to the center

for(int i=0; i < numPoints; ++i)
{
xn = nrand.next();
yn = nrand.next();

xr = rand.nextDouble();
yr = rand.nextDouble();

zn = (xn * xn) + (yn * yn);
if(zn <= 1.0)
inNaiveCircle++;

zr = (xr * xr) + (yr * yr);
if(zr <= 1.0)
inRandCircle++;
}

// calculate the Pi approximations
double naivePi = approxPi(inNaiveCircle, numPoints);
double randomPi = approxPi(inRandCircle, numPoints);

// calculate the % error
double naiveError = calcError(naivePi);
double randomError = calcError(randomPi);

System.out.println("Naive Pi Approximation: " +
naivePi + ", Error: " + naiveError);
System.out.println("Random Pi Approximation: " +
randomPi + ", Error: " + randomError);
}

static double approxPi(int inCircle, int totalPoints)
{
return (double)inCircle / totalPoints * 4.0;
}

static double calcError(double pi)
{
return (pi - Math.PI)/Math.PI * 100;
}
}

Results


Run the simulator several times and you will see that Java's built-in PRNG seems to outperform the naive implementation, but not by much. Neither performs particularly well, but Monte Carlo simulations are only expected to be close, not exact. Here are my results after ten runs of the simulation.












Naive RandomJava Random
PiError(%)PiError(%)
3.122-0.62373.1308-0.3435
3.15160.31853.1332-0.2671
3.1272-0.45813.1352-0.2035
3.16920.87883.1352-0.2035
3.15240.34403.14160.0002
3.1168-0.78923.1340-0.2417
3.17240.98063.1040-1.1966
3.16120.62413.1244-0.5473
3.14480.10213.14280.0384
3.1052-1.1583.16280.6751


At least a small part of the imprecision of these results can be attributed to the fact that I only took 10,000 random points in each sample. A rule of thumb in Monte Carlo simulations is that for every 100X increase in data points, you'll get a 10X increase in the precision of your results. Since I took only 10,000 random points (100 * 100), I only got 2 digits of precision, with the third digit fluctuating.

Try increasing the number of random points to 1,000,000 and you should see that the third digit remains fixed over several runs of the program. The really interesting thing revealed is that our naive implementation continues to perform nearly as well as Java's built-in PRNG. This leads us to the conclusion (which can be easily verified) that Java's PRNG uses the same linear congruential method for generating random numbers as our naive implementation. The only significant difference between the two is that Java's implementation will be able to generate much longer sequences of random numbers before it starts to repeat itself.

Further Investigation

As I mentioned before, there are many statistical tests that can be used to measure the relative randomness of a sequence. I've only covered one of those tests in detail, but there are libraries available like the Diehard Battery of Tests of Randomness and ENT that include a wide variety of tests, and guidelines for interpreting them. If your application depends on randomness, I recommend evaluating your random number generator with one of these test suites.

Friday, November 7, 2008

NetBeans PMD plugin

I was installing NetBeans on a new computer recently (and prompted by a question on StackOverflow), so it came to my attention that, due to the blazing fast speed of NetBeans development, the instructions for installing the NetBeans PMD plugin are a little outdated. Here's an updated set of instructions*.

1. Download the latest PMD release from SourceForge.
2. Unzip the zip file to any directory. I put mine in C:\Program Files\Java\pmd-netbeans60-2.2.1, right next to my JDK directory. You'll see that the zip file contained a .nbm file that encapsulates the plugin.
3. Run NetBeans and click Tools -> Plugins
4. Go to the Downloaded tab on the Plugins dialog.
5. Click on the Add Plugins... button at the top of the tab.
6. Navigate to the directory where you unzipped the PMD plugin zip file.
7. Select the file named pmd.nbm.
8. Click the Open button.

You'll get a dialog saying that the plugin isn't signed, asking you whether you want to accept it anyway or cancel the installation. You'll need to accept it without a signature in order to use the plugin. You'll need to restart NetBeans after installation is complete.

You can run PMD by selecting a single source code file or an entire source package, then selecting Tools -> Run PMD (or Ctrl-Alt-P) from the main NetBeans menu.

To change from the default rule set go to Tools -> Options on the main NetBeans menu. On the Options dialog, select the Miscellaneous toolbar button, then the PMD tab. On the PMD tab you can press the Manage Rules... button to change the default ruleset, or press the Manage Rulesets... button to create a custom ruleset of your own.

*Note: I'm doing the installation for NetBeans 6.1 running on Windows XP as I write these instructions. I've verified these instructions using NetBeans 6.0.1 on Ubuntu.

Tuesday, August 26, 2008

Trim Tokens

When working with a tokenized string, like those found in comma-separated value (CSV) files, it's common to encounter this problem. What do you do when someone edits the file by hand, and inserts extra space characters to make the file more human-readable? Add a space to the token? That's no good because then all of your files have to match the "new and improved" format.

For example, take the following snippet of CSV file.

username, password,home folder,default editor, favorite color,web address

Notice that the delimiter is inconsistent in this example. Sometimes I have tokens separated with a single comma (",") and sometimes with a comma followed by a space (", "). If the delimiter were consistent it would be a simple matter to get all tokens with the following code:

String[] tokens = line.split(",");

First of all, let's note how much simpler this is than the old method of using a StringTokenizer to loop through the text scanning for more tokens. String's split method added in the Java 1.4 release is a great improvement. The second thing you should note is that the split method accepts one argument, and that argument is a regular expression. This should be a clue to solving our CSV formatting problem. How do we specify that the delimiter in our file is a comma that might sometimes be followed by a space? By harnessing the power of regular expressions. (Ok, that's overstating the case by quite a bit. We're really only harnessing a tiny fraction of the power of regular expressions.)

String[] tokens = line.split(",\\s*");

That says split the line on any comma followed by zero or more spaces (check out Mastering Regular Expressions for an in-depth guide to regular expression syntax). This single line of code should have the desired effect of splitting the line into the following array.

username
password
home folder
default editor
favorite color
web address

Try it out by creating a simple class that reads a single line of comma-delimited text and prints out the tokens. If you really want to see what an improvement String's split method brings, try writing the same function using a StringTokenizer instead.

Saturday, August 9, 2008

Stop a thread that's accepting connections

A common approach to implementing a server is to set up its main loop to accept connections from clients, then create separate threads to handle each connection.

But how do you shut down a thread that's blocked in the wait state? It's not enough to simply set the running flag to false, breaking it out of its main loop, as that would leave the server waiting for one last connection before it lets go of its resources and shuts down. The following code shows you how.

public class SimpleServer extends Thread {

private volatile boolean running = false;
ServerSocket serverSock = null;
private int serverPort = 8080;

public SimpleServer (int serverPort) {
this.serverPort = serverPort;
}

/** Begin listening for connections from subscribers. */
public void run() {
System.out.println( "Simple Server started." );

try {
serverSock = new ServerSocket( serverPort );
} catch ( IOException e ) {
System.err.println( e.getMessage() );
}

running = true;
// main loop of the thread
// listens for new subscribers
while( running ) {
Socket sock = null;
try {
// blocks while waiting
sock = serverSock.accept();

// handle the new socket connection
}
catch ( IOException ioe ) {
System.err.println( ioe.getMessage() );
}
finally {
try {
sock.close();
}
catch ( IOException ioe ) {
System.err.println( ioe.getMessage() );
}
}
}
}

/** Check the running flag. */
public boolean isRunning() {
return running;
}

/** Stop the server listen thread. */
public void shutDown() {
running = false;
try {
// open a connection to the server socket,
// because it is blocking on accept
new Socket( serverSock.getInetAddress(),
serverSock.getLocalPort() ).close();
System.out.println("Server shut down normally.");
}
catch(IOException ioe) {
System.err.println( ioe.getMessage() );
}
}
}

The interesting technique here can be found in the shutDown method. After setting the running flag to false we open one more socket connection on the listening port, then immediately close it. This allows the server application to terminate immediately and gracefully.

Thursday, August 7, 2008

Avoid NPE when comparing strings

By now everyone knows that you should use the equals method when comparing two objects in Java (as opposed to using the == operator). Strings are no different. But what happens when you compare a null reference to a string literal, like so:

String myRef = null;
if ( myRef.equals("literal") ) {
// do something
}

If you run this code you'll see you get a Null Pointer Exception for calling a method on a null reference. I've seen some developers get around this problem by checking for null before calling equals.

String myRef = null;
if ( myRef != null && myRef.equals("literal") ) {
// do something
}

This cleverly uses the short-circuit property of the && operator. If the first part of the condition is false the second part won't be evaluated, avoiding the NPE. Like most clever code, this is not the best way to go about it. I learned a better way when reviewing a colleague's code. Just take the original condition and switch it around so you call equals on the literal, and pass the (possibly null) reference as a parameter.

String myRef = null;
if ( "literal".equals(myRef) ) {
// do something
}

This avoids the NPE because a string literal can never be null. If the reference is null, the condition returns false, as expected. This solution is also a little bit shorter and clearer than the first one. The lesson to be learned here is that if you have to resort to "clever" tricks to get something done, with just a little bit of lateral thinking you can probably find a cleaner, simpler way.

Sunday, August 3, 2008

Implementing equals in Java

Update: I made reference to Josh Bloch's Effective Java in this article. Those references are to the first edition of the book and should be disregarded. The second edition addresses every issue that I (and others) considered a shortcoming concerning the implementation of the equals method from the original edition. If you are a Java programmer, you should probably stop reading this and just read the second edition of Josh's book instead.

Second update: There's also an excellent and detailed article online on Jave equality by Martin Odersky, Lex Spoon, and Bill Venners: How to Write an Equality Method in Java.

Many beginning Java programmers get confused about the difference between the equals operator (==) and the equals method. This confusion can probably be traced back to the fact that ==, like so many things in Java, works differently with primitives than it does with object references. The == operator in Java works with primitives by comparing their values, but it works with objects by comparing their references. This means that == will always work with primitives, but it will rarely work as expected with objects. Remember that references in Java point to a location on the memory heap. Two references that point to the same object are equal, but two references that point to two different objects are never equal, even if they hold the same value.

Another source of confusion may be from the default implementation of the equals method itself. Every class in Java inherits a default equals implementation from the Object class. Object's equals method simply compares references, so the default implementation gives the exact same behavior as the == operator. That's why it's a good idea to override the equals method in any classes you create that need more than the default behavior.

Unfortunately, implementing equals is harder than it at first may seem. Many beginning developers (and even a few experienced ones) naively cast to the correct type and compare significant fields without giving due consideration to the general equals contract. Joshua Bloch spends ten worthwhile pages on the subject in his book Effective Java, and some would argue that he still doesn't get it exactly right. In addition to the properties laid out in the general equals contract, there are also a few object design decisions that need to be taken into account to insure correct equals behavior. I'll try to explain all of these issues.

By general contract, the equals() method in Java must be reflexive, symmetric, transitive, consistent, and any non-null reference must return false. In other words, for arbitrary values of a, b, and c, the following tests must always pass:

// reflexive property
assertTrue( a.equals(a) );

// symmetric property
assertTrue( a.equals(b) == b.equals(a) );

// transitive property
if ( a.equals(b) && b.equals(c) ) {
assertTrue( a.equals(c) );
}

// consistency property
assertTrue( a.equals(b) == a.equals(b) );

// non-null property
assertFalse( a.equals(null) );

It would be difficult to get reflexivity and consistency wrong without trying. A very simple test for null is all that's needed to make sure your equals method returns false when a null parameter is passed. The symmetry and transitivity properties, on the other hand, are difficult to get right without giving some serious thought to each.

For example, both Java Practices and Joshua Bloch recommend the following steps for implementing equals:

1. Use this == that to check reference equality
2. Use instanceof to test for correct argument type
3. Cast the argument to the correct type
4. Compare significant fields for equality

Given this template, the equals method for a simple 2-dimension Point class might look like the following:

class Point {
private int x;
private int y;

...

public boolean equals(Object obj) {
// check for reference equality
if(this == obj) return true;

// type check
if( !(obj instanceof Point) ) return false;

// cast to correct type
Point p = (Point)obj;

// compare significant fields
return (this.x == p.x && this.y == p.y);
}
}

Step one fulfills the reflexivity requirement of the equals contract. It also serves as an optimizing step. If the parameter refers to this object, obviously they are equal and you don't need to waste any more time comparing them. This saves time particularly when the comparison (step four) is costly.

Step two uses instanceof to check that the argument is of an acceptable type. This is usually the same type as this object, but could be a super type or interface. Consider comparing two Collections to each other. You may wish to consider two Lists equal if they have the same elements, regardless of whether one is a LinkedList and the other an ArrayList. Simply implementing the List interface should be enough to correctly pass this step, then safely cast to the same type in step three. Notice also that this method doesn't explicitly check to see if the argument is null. That's because there's an implicit check in step two. The instanceof operator will return false if its second argument is null.

It's not hard to prove that this implementation of equals satisfies the symmetric and transitive properties of the equals contract. A few simple test cases should show that for any two Point objects, if x and y are equal, the equals method will return equal, and if x or y are not equal it will return false. But there is a very subtle bug lurking in this implementation. You have to ask yourself, "What happens if I extend this class by adding a significant field?" By "significant field", I mean a field that impacts equality. One that should be taken in to account by the equals method.

Let's look at an example. Say I want to extend this class to make a 3-dimensional Point by adding a z dimension. In this case the Point3D equals method needs only to call the Point equals method and add its own comparison of the z-dimension instance variable.

class Point3D extends Point {
private int z;

...

public boolean equals(Object obj) {
if(!(obj instanceof Point3D)) return false;
Point3D p3d = (Point3D)obj;
return super.equals(obj) && this.z == p3d.z;
}
}

This implementation works for two Point3D objects the same way the Point equals method works for two Point objects. The problem is that it breaks the symmetric property of the equals contract when you mix objects of the two types. Consider the following:

Point p = new Point(4, 2);
Point3D p3d = new Point(4, 2, 3);
p.equals(p3d); // returns true
p3d.equals(p); // return false

The problem is that Point3D instanceof Point returns true, while Point instanceof Point3D returns false, violating the symmetric property.

To his credit, Joshua Bloch goes on in his book to explain a technique using composition that offers a solid workaround to the problems inherent in using instanceof. There is another popular approach to implementing equals that also circumvents these problems.

1. Test for a null argument
2. Use if (getClass() != obj.getClass()) to test for correct argument type
3. Cast the argument to the correct type
4. Compare significant fields for equality

Using this slightly different template the equals method for our simple Point class now becomes:

public boolean equals(Object obj) {
// check for null reference
if(this == null) return false;

// type check
if(this.getClass() != obj.getClass()) return false;

// cast to correct type
Point p = (Point)obj;

// compare significant fields
return (this.x == p.x && this.y == p.y);
}

As you can see, the two approaches only differ in the first two steps. First, we replace the optimizing step with a test for null. The null test is required because in the second step we're no longer using instanceof, it's been replaced with a call to getClass. This fixes the problem with symmetry that we experienced in the first approach because the getClass method will always return false if the parameter is not the exact same type as the object class. Super class or subclass parameters return false, preserving the symmetric property. Be aware that this can lead to surprising behavior when two objects are equal in all significant fields, but are considered unequal because they aren't the same type (refer back to the LinkedList, ArrayList example I gave earlier).

So which of these two approaches to implementing equals should be preferred? The questions to ask when designing your class is whether you're designing it to be extended or not, and whether it is important for classes of different types (but the same interface) to adhere strictly to the equals contract. In most cases strict adherence to the equals contract should be preferred, and so the getClass approach should be used. The only times you should consider using instanceof in your equals methods are when objects of a subclass must be comparable to objects of their base class type, or if two objects that implement a common interface must be considered equal based on their state rather than just their type. In both these cases, be well aware of what properties of the general equals contract you may be violating. It's also a good idea to thoroughly document these points in your code and in your API documentation.

Tuesday, July 29, 2008

Rotate an image in Java


In Python, many complex image functions are made simple using the Python Imaging Library (PIL). For example, I can load an image from file, rotate it any number of degrees, and display the image in just four lines of Python code.


from PIL import Image
pic = Image.open("wire.png")
pic.rotate(45)
pic.show()

Performing the same task in Java, however, requires the involvement of several classes and a slightly deeper understanding of graphics processing. I feel that Sun's decision to break everything up into hundreds of classes offers great flexibility for me to combine classes to come up with my own solution to a given problem. This approach may be verbose, but it does lead to a better understanding of the underlying algorithms involved.


import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.net.URL;

public class RotateImage extends Applet {

private Image image;

AffineTransform identity = new AffineTransform();

private URL getURL(String filename) {
URL url = null;
try {
url = this.getClass().getResource(filename);
}
catch(Exception e){}
return url;
}

public void init() {
image = getImage(getCodeBase(), "image.jpg");
}

public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
AffineTransform trans = new AffineTransform();
trans.setTransform(identity);
trans.rotate( Math.toRadians(45) );
g2d.drawImage(image, trans, this);
}
}

This looks a lot worse than it is. There are 22 lines of code here (not counting white space and curly braces), but the majority of them are spent on importing Java libraries and loading the image. Only six of them are spent rotating and displaying the image.

The most complicated part of the code is the AffineTransform object. According to Sun's AffineTransform API, "The AffineTransform class represents a 2D affine transform that performs a linear mapping from 2D coordinates to other 2D coordinates that preserves the "straightness" and "parallelness" of lines." If you experiment a little with this class (or just continue reading the API), you'll see that it can be used not just to rotate, but also to scale, flip, and shear an image as well.