1

I'm trying to Write a method called scaleByK that takes an ArrayList of integers as a parameter and replaces every integer of value k with k copies of itself. For example, if the list stores the values [4, 1, 2, 0, 3] before the method is called, it should store the values [4, 4, 4, 4, 1, 2, 2, 3, 3, 3] after the method finishes executing. Zeroes and negative numbers should be removed from the list by this method. the problem is that I'm getting error of java heap space.

public class Lab1construct2 {

    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(4);
        list.add(1);
        list.add(2);
        list.add(0);
        list.add(3);

        Lab1construct2 myprogram = new Lab1construct2();
        myprogram.scalebyk(list);
        System.out.print(list);
    }

    public void scalebyk(ArrayList<Integer> list) {
        int j = 0;
        while( j < list.size()) {
            int elm =list.get(j);
            for(int i=1; i<=elm; i++) {
                list.add(elm);
            }
            j = j + list.get(j);
        }
    }
}
2
  • 5
    Your loop will never end, leading to an ever growing list, eventually leading to an out-of-memory error. Commented Feb 25, 2020 at 7:25
  • ohhh yeah i got it thank you so much Commented Feb 25, 2020 at 7:27

2 Answers 2

4

You keep inserting copies of processed elements to the back of the same list which you are reading. So after you done processing of the original elements you start to process their copies, then copies of their copies, etc. This never stops and you get heap overflow. Create a new list which will keep the result and return it from the method, don't modify the current list.

public List<Integer> scalebyk(ArrayList<Integer> list) {
  List<Integer> result = new ArrayList<Integer>();
  for (Integer element : list) {
    for (int i = 0; i < element; i++) {
      result.add(element);
    }
  }
  return result;
}
Sign up to request clarification or add additional context in comments.

Comments

2

It is because your code would never terminate. Following would be the flow of your scaleByk function:

  • First element is 4, j=0 hence 4 new elements will be added to the list with the value of 4

  • j=4 but is still less than list.size() as size is increased by 4 in the previous step. Again it will trigger the addition of 4 elements with value 4.

This cycle will keep repeating till you run out of the heap space allocated to your program.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.