Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Charting Unknown Waters in JDK 1.4 : Page 2

Java Specialist Dr. Heinz Kabutz has been digging through the classes in the java.util.* package of the JDK 1.4. This article highlights some of the gems he discovered right away.


advertisement

WEBINAR: On-Demand

Unleash Your DevOps Strategy by Synchronizing Application and Database Changes REGISTER >

Introducing RandomAccess, A New Tag Interface
A highly paid software developer once wrote code along the lines of the following snippet. Take a moment to thoroughly read the code and understand it:

/** @author Mr M.O.Nument */ import java.util.*; public class ListSearching { private List names = new LinkedList(); public void f() { for (int i=0; i<size(); i++) { if (names.get(i) == "Heinz") System.out.println("Found it"); } } private int size() { int result = 0; Iterator it = names.iterator(); while(it.hasNext()) { result++; it.next(); } return result; } }

Dont be too quick to judge the programmer. In his defense, a lot of code had to go between f() and size(), so the problem was not as obvious as it now appears. Also, the list was always very short, so performance was not an issue either.



JDK 1.4 introduces a new tag interface called RandomAccess (like java.io.Serializable) into the java.util package. It allows classes such as Collections to optimize their algorithms in the case where the following code:

for (int i=0, n=list.size(); i < n; i++) list.get(i);

runs faster than the following loop:

for (Iterator i=list.iterator(); i.hasNext(); ) i.next();

What I found interesting was that the algorithms always treat the collections as RandomAccess unless they are bigger than some threshold. This makes a lot of sense, because I have often found algorithms that I thought to be faster for linked lists actually being slower (see Issue 024 of The Java(tm) Specialists' Newsletter). The values of the thresholds are of course not configurable and are approximations based on empirical data (i.e., experiments) that would work well with the LinkedList.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date