I created a code that basically just tests the approx. run-time of ArrayLists. However, the code will not compile if a line of code is moved spots. Here is the code that compiles.
public class ArrayTest {
public static void main(String []args) {
ArrayListTest();
}
private static void ArrayListTest() {
//initializes random variable, accumulator and iterator and ArrayList
Random rand = new Random();
Float accum = 0F;
ArrayList<Float> al = new ArrayList<>();
//finds time of program pre-running
long startTime = System.currentTimeMillis();
//Populates ArrayList
for (int i = 0; i < 20000000; i++) al.add(rand.nextFloat());
//finds time of program post-running
long endTime = System.currentTimeMillis();
//Iterates through ArrayList, summing elements
Iterator<Float> itr = al.iterator();
while(itr.hasNext()) {
accum += itr.next();
}
//Finds time of summing ArrayList
long sumEndTime = System.currentTimeMillis() - endTime;
//Prints meaningful conclusion
System.out.print("ArrayList takes: " + (endTime - startTime) / 1000.0 + " seconds to initialize.\n");
System.out.print("ArrayList takes: " + (sumEndTime / 1000.0) + " second to sum. \n");
}
}
However, if you move the "Iterator itr = al.iterator();" to right after the declaration of the arraylist, it doesn't compile. Why is this?