|
Reading Elements from End to Beginning
Here's the algorithm:
Repeat from position N-1 to 0:
Read element a the given position
End Repeat
|
Object type
|
Comments
|
|
array
|
loop through the array using an index from N-1 to 0
|
|
List
|
use the get(index) method N times
|
|
HashMap
|
use the keys Integer(N-1) to Integer(0)
|
The test running with N=1 000 000 gave almost identical results as when reading from start to end.
Updating Elements at Random Positions on a List
Here's the algorithm:
Repeat N times
Replace element at a random position in the list
End Repeat
|
Object type
|
Comments
|
|
array
|
use array[random index] = value
|
|
List
|
use the set(random index, element) method N times
|
|
HashMap
|
use Integer(random index) as key
|
The test runs yielded the following results for N=100 000. All times measured were divided by the times measured for the array type.
|
Object type
|
Relative time
|
|
array
|
1
|
|
Vector
|
1.1
|
|
ArrayList
|
1.1
|
|
LinkedList
See note 1)
|
not completed
|
|
HashMap
|
7.3
|
Results:
- This uses up too much cpu time.
- The Vector and ArrayList use almost the same time as the array. The reason for this, of course, is that the size of the underlying arrays is fixed. The HashMap still has a fine performance.
Situational Ethics
The measured times show that for random operations within a list, it's preferable to use the array or the ArrayList. There's no real difference in performance between the array and the ArrayList, so if you need the extra features of an ArrayList, then it's the obvious choice.
You should only consider using LinkedList when your operations work on the ends of the list. Another option to consider might be the new Queue class-- when only the top element of a list is of interest.
When the index or key to the list is not an integer, HashMap is the only choice, and as you've seen, its performance is quite good.
Happy coding!
Resources
- Click here to download the source code.
New on the Java Boutique:
New Review:
Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling
API boasts simplicity, ease-of-integration, a well-rounded feature
set, and it's free!
New Applet:
Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA
sequences into three useful formats.
Elsewhere on internet.com:
WebDeveloper Java
Lots of Java information on webdeveloper.com
WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.
ScriptSearch Java
Hundreds of free Java code files to download.
jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.
|