Upon instantiation, an ArrayList contains zero elements initially, but elements can be added dynamically using add(). Elements not yet added do not exist until explicitly inserted.
Passing as argument - a copy of the reference to the instantiated ArrayList is passed to the method. This means that any changes made to the elements inside the method persist outside the method. The exception is if the argument is assigned to reference a different ArrayList inside the method.
Q18: Put the following code in order to create a program that will declare and instantiate an ArrayList of 20 random Integer values between 1 and 100 and then calculate and print the average of the first 10 numbers.
import java.util.*;
public class main{
public static void main (String[] args) {
---
Random r = new Random();
ArrayList<Integer> arr = new ArrayList<Integer>();
int sum = 0;
---
for (int i = 0; i < 20; i++) {
arr.add(r.nextInt(100) + 1);
System.out.println("arr.get("+i+") is " + arr.get(i));
}
---
for (int i = 0; i < 10; i++)
---
sum += arr.get(i);
---
System.out.println("Avg of first 10 is " + sum/10.0);
---
}
}
Q19: Put the following code in order to create a program that will declare and instantiate an ArrayList of 20 random Integer values between 1 and 100 and then calculate and print the average of the last n numbers.
import java.util.*;
public class main{
public static void main (String[] args) {
---
Random r = new Random();
int size = 20;
ArrayList<Integer> arr = new ArrayList<Integer>();
int sum = 0;
int n = r.nextInt(size);
---
for (int i = 0; i < 20; i++) {
arr.add(r.nextInt(100) + 1);
System.out.println("arr.get("+i+") is " + arr.get(i));
}
---
if (n <= 0)
---
System.out.println("No numbers to average.");
---
else {
---
for (int i = 20-n; i < 20; i++)
---
sum += arr.get(i);
---
System.out.println("Avg of last n is " + (sum * 1.0)/n);
---
}
---
}
}