KaiquanMah's picture
Create 6B. Create a list
59719c2 verified
raw
history blame
2.04 kB
Write the method
ArrayList<Integer> createList(int start, int end)
...which takes as parameters the start and end values of the list.
The method generates a new list containing, in order, all the elements between the given points, one step apart.
As usual, the START sub-item is INCLUDED in the list, but the END sub-item IS NOT.
Note that the list must be created BACKWARDS IF the STARTING sub-item is GREATER than the ending sub-item.
See the sample performances for an example.
Examples on method calls:
public static void main(String[] parameters){
System.out.println(createList(1,10));
System.out.println(createList(10,1));
}
Program outputs:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 9, 8, 7, 6, 5, 4, 3, 2]
===============================
import java.util.Random;
import java.util.ArrayList;
public class Test{
public static void main(String[] args){
final Random r = new Random();
Object[][] p = {{1,4}, {100,106}, {5,0}, {90,80}};
for (Object[] pa : p) {
System.out.print("Testing with parameters ");
System.out.println(pa[0] + ", " + pa[1]);
System.out.println(createList((Integer) pa[0], (Integer) pa[1]));
System.out.println("");
}
}
public static ArrayList<Integer> createList(int start, int end) {
ArrayList<Integer> list = new ArrayList<>();
// ascending order
if (start < end) {
for (int i = start; i < end; i++) {
list.add(i);
}
}
// start > end
// descending order
// start >> start-1 >> ... >> (excluding) 'end'
else {
for (int i = start; i > end; i--) {
list.add(i);
}
}
return list;
}
}
Testing with parameters 1, 4
[1, 2, 3]
Testing with parameters 100, 106
[100, 101, 102, 103, 104, 105]
Testing with parameters 5, 0
[5, 4, 3, 2, 1]
Testing with parameters 90, 80
[90, 89, 88, 87, 86, 85, 84, 83, 82, 81]