Skip to content
Advertisement

Method that fills the gap between an ArrayList in Java

I’m making a method called fillList. The method will require an arrayList in order to work and the output will be void. What the method is supposed to do is to fill the gaps between the numbers of the List.

Example:

Input:

4 8 5 9

Output:

4 5 6 7 8 7 6 5 6 7 8 9

The code I have so far is this:

public static void fillList(ArrayList<Integer> List) {
        for(int i = 0; i < List.size(); i++) {
           if(List.get(i) < List.get(i+1) ) {
             List.add(List.get(i+1));
           }  else if(List.get(i) > List.get(i+1)) {
               List.add(List.get(i-1));
           }
        }
    } 

My idea was to add 1 to the value of the first element if the first element was less than the second element in the List. For example if the first element is 4 then the code would add a 5 to the list and stop once the number added was equal to one less than the second element. And basically do the opposite if the first element was more than the second element.

I don’t know how to stop this loop until the numbers that are being added reach the second element of the list. I am not confident about my code as well I’m pretty sure I am making an error I’m not seeing.

Advertisement

Answer

To update the list while iterating over its indices, you can use method List.add(int index, E element), which expects an index and a new element to insert.

While iterating, you need to compare two adjacent elements and insert a new one under the following conditions:

  • Left element is less than the right one and difference between them is greater than 1. A new element should be equal left + 1.

  • Left element is greater than the right one, and they differ more than by 1. A new element should be equal left - 1.

Also have a look at the nicely illustrated answer by @yezper. And as a general advice: draw before coding in order to understand the algorithm better.

That’s how implementation might look like:

public static void fillList(List<Integer> list) {
    for (int i = 0; i < list.size() - 1; i++) {
        int left = list.get(i);
        int right = list.get(i + 1);
        if (left < right && left + 1 != right) {
            list.add(i + 1, left + 1);
        } else if (left > right && left - 1 != right) {
            list.add(i + 1, left - 1);
        }
    }
}

main()

public static void main(String[] args) {
    List<Integer> list1 = new ArrayList<>(List.of(4, 8, 5, 9));
    fillList(list1);
    System.out.println(list1);
}

Output:

[4, 5, 6, 7, 8, 7, 6, 5, 6, 7, 8, 9]
Advertisement