When declaring an ArrayList, the datatype stored in the container is specified inside of <>, and the data type must be the name of a class (no primitive data types)
The parameter to the method get represents the index in the ArrayList. The size of the ArrayList is the number of elements contained. If the ArrayList is initially empty, the size is 0.
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 one exception to this is if you assign the argument to reference a different ArrayList in memory.
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);
---
}
---
}
}