|
|
|
How many interfaces are there in the JDK that have no fields and no methods? What are these interfaces used for? Read on in our "Fast Random Access" article from our "Learning From Code" series.
Published February 2004, Author Jack Shirazi
Page 1 of 2
next page: How is RandomAccess used?
In the "Learning From Code" series, we examine existing code for techniques that offer a performance advantages. Such advantages have already been tried and tested, and often provide very interesting tuning techniques.
Here's a nice trivia question to try out on your colleagues. Name three interfaces in the Java SDK distribution which have no fields or methods in them. Your first response might be: "what use is an interface with no fields or methods?" But if you've done more than a little Java programming, you have probably already used two such interfaces: Serializable
and Cloneable
.
These are known as marker interfaces. They do not define behavior directly, instead they "mark" a class as having a particular capability. In the case of Serializable
the interface specifies that if the class is serialized using the serialization I/O classes, then a NotSerializableException
will not be thrown (unless the object contains some other class that cannot be serialized). Cloneable
similarly indicates that the use of the Object.clone()
method for a Cloneable
class will not throw a CloneNotSupportedException
.
Java SDK version 1.4 introduced a new marker interface, java.util.RandomAccess
, for optimizing List
performance. What is the use of this interface? The RandomAccess
interface identifies that a particular java.util.List
implementation has fast random access. More accurately, the RandomAccess
interface identifies List implementations which are faster to iterate using the List.get()
method rather than using the Iterator.next()
method.
The two types of access are shown in the following code examples:
|
|
There is a third loop which alters the iterator loop to avoid the repeated Iterator.hasNext()
test on each loop iteration, appropriate for collections whose size will not be changing during the loop iteration:
|
This last loop relies on the fact that if the loop size remains the same, you can simply count the accessed elements without testing at each iteration whether the end of the list has been reached. The last loop is generally faster than the previous loop with the Iterator.hasNext()
test. In the context of the RandomAccess
interface, the first loop using List.get()
should be faster than both the other loops that use Iterator.next()
for a list to implement
RandomAccess
.
Continued on next page
Page 1 of 2
next page: How is RandomAccess used?