CSCI 200 Spring 2010
Laboratory Exercise 2 - Iterators with Java Container Classes
Goal
Gain practice with using Iterators with Java's ArrayList, TreeMap, and HashMap classes.
Grading
The lab exercise is worth 10 points. There is no design document for this lab.
Exercise Details
Write a program to use the Math.random() function to populate an ArrayList object, HashMap object
and TreeMap object using Double
objects. Generate numbers between 0 and 1, of the following sizes:
100, 1000, 10000, 100000, 1000000 (one million). Then use a for loop to iterate through your Collection objects,
noting the required time for each. For the smaller sizes, you may have to repeat the
operation (moving through the whole map) multiple times to have it take enough CPU time to be
measurable. Write down the values for all sizes for the 3 types of Collections and show these values
and your code to your TA.
Do the times make sense? Explain your answer to your TA.
For the HashMap, read the Java API reference documentation's discussion of how to compute
the HashMap size, so that you initialize it to the proper size for best performance.
Measuring CPU time
To time an operation in Java, just call System.currentTimeMillis() before and after
the operation to be measured. You then can compute the difference in the 2 values.
long startTime = System.currentTimeMillis();
//Do the operation - iterate through the map
long endTime = System.currentTimeMillis();
System.out.println("Elapsed time:" + endTime - startTime );