Ranit Bagchi
Ranit Bagchi

Reputation: 23

Arraylist Java showing out index out of bounds

My goal is to create a new instance where the first 2 elements are the original elements and after that is the median of last 3 elements.For example, [5,2,9,1,7,4,6,3,8] becomes [5,2,5,2,7,4,6,4,6].

My way to solve this problem is to create 2 new array lists where one is the subarray between 3 elements starting from index 2 and having (i-2,i+1), sort and lastly get the index 1 of the new subarray into my new array list. However this runs into an index out of bounds error.

import java.util.*;

 public class P2J4
{
    public static void main (String[]args){
       List<Integer> items = Arrays.asList(16, 42, 99, 17, 2);
       ArrayList<Integer>newarr=new ArrayList<>();
       newarr.add(0,items.get(0));
       newarr.add(1,items.get(1));
    
       for(int i=2;i<items.size();i++){
          
           List<Integer> sub = items.subList(i-2,i+1);
      
           Collections.sort(sub);
           newarr.set(i,sub.get(1));
        }
    }
}

Upvotes: 0

Views: 797

Answers (1)

Liftoff
Liftoff

Reputation: 25392

ArrayList.set only updates existing elements. It does not append elements if the given index is out of bounds. You need to use ArrayList.add or add enough elements beforehand so that newarr.size() == items.size()

newarr.add(sub.get(1));
import java.util.*;

 public class P2J4
{
    public static void main (String[]args){
       List<Integer> items = Arrays.asList(16, 42, 99, 17, 2);
       ArrayList<Integer>newarr=new ArrayList<>();
       newarr.add(0,items.get(0));
       newarr.add(1,items.get(1));
    
       for(int i=2;i<items.size();i++){
          
           List<Integer> sub = items.subList(i-2,i+1);
      
           Collections.sort(sub);
           newarr.add(sub.get(1));
        }
    }
}

Upvotes: 3

Related Questions