简体   繁体   English

Arraylist Java 显示超出范围的索引

[英]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] .我的目标是创建一个新实例,其中前 2 个元素是原始元素,之后是最后 3 个元素的中位数。例如, [5,2,9,1,7,4,6,3,8]变为[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.我解决这个问题的方法是创建 2 个新数组列表,其中一个是从索引 2 开始并具有(i-2,i+1)的 3 个元素之间的子数组,排序并最后将新子数组的索引 1 放入我的新的数组列表。 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));
        }
    }
}

ArrayList.set only updates existing elements. ArrayList.set仅更新现有元素。 It does not append elements if the given index is out of bounds.如果给定的索引超出范围,它不会 append 元素。 You need to use ArrayList.add or add enough elements beforehand so that newarr.size() == items.size()您需要使用ArrayList.add或预先添加足够的元素,以便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));
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM