Java Puzzlers: Phantom Reference Menace, Attack Of The Clone, & Revenge Of The Shift
by Milinda Lakmal
In this presentation, Joshua Bloch and William Pugh describes eight short Java programs with curious behavior. Things discussed in this presentation will help you a lot, if you are a Java developer.
Following is the list of problems and summary of things you can learn from studying those problems.
1. The Joy Of Sets
What is the out put of following program.
Moral of the above problem:
- Collection<E>.remove takes Object, not E
- Integral arithmetic always results in int or long
- Avoid mixing types
- Avoid short; prefer int and long
2. More Joy of Sets
Out put of the above program will depends on the whether you are connected to internet or not. This happens because URL’s equals and hashCode are broken.
Things we can learn from above problem:
- Do not use URL as a Set element or Map key
- equals and hashCode aren’t well defined
- They do not obey their general contracts
- Use URI instead of URL
- Make URL from URI as neccessary
- equals should not depends on the environment
3. Racy Little Number
How often does the following test pass.
Moral of the problem:
- JUnit does not support concurrency
- You must provide your own way of handling concurrency
- If you don’t you will get a false sense of security
4. Elvis Lives Again
What does following program print?
Moral of the problem:
- Wrapped primitives aren’t primitives
- Prefer primitives to wrapped primitives
- Auto-unboxing can occur when you leas expect it
- It can cause NullPointerException
- Never use Boolean as a three-valued return type
- Almost guarantees NullPointerException
- Watch out for circularities in class initialization
- Construct instance at end of class initialization
5. Mind The Gap
What does following program prints?
Moral of the problem:
- The skip method is hard to use and error prone.
- Use your skipFully(you will learn about it during the presentation) instead of skip
- More generally, if an API is broken, wrap it
- For API designers
- Don’t violate the principle of last astonishment
- Make is easy to do simple things