java sublist removal

aretai picture aretai · Jan 25, 2012 · Viewed 9.7k times · Source

I'm trying to create a list of objects and then a sublist and then delete all the elements in the sublist and then once again display the main list. However when I try to remove elements from a sublist I get error at runtime indexoutofbounds and unknown source. How to fix that so that the app works?

import java.util.*;

class Eval{
    Eval(){         
    }   
}

public class Ch11Ex7 {
    public static void main(String[] args){ 

        Eval e1 = new Eval();
        Eval e2 = new Eval();
        Eval e3 = new Eval();
        Eval e4 = new Eval();
        Eval e5 = new Eval();

        Eval[] eva = {e1, e2, e3, e4, e5};

        //ArrayList<Eval> ev = new ArrayList<Eval>(Arrays.asList(eva));
        List ev = Arrays.asList(eva);
        List<Eval> sub = ev.subList(1, 3);  
        for(int i=0; i< ev.size() ; i++)
              System.out.println(ev.get(i));        
        System.out.println("Sublist");  
        for(int i=0; i< sub.size() ; i++)
              System.out.println(sub.get(i));   
        System.out.println("Remove element");
        sub.remove(2);
    }
}

Answer

Tudor picture Tudor · Jan 25, 2012

The second index of subList is exclusive, so if you want the elements between [1..3] you need to use:

List<Eval> sub = ev.subList(1, 4); 

Furthermore, what you are trying to do will not work anyway, because the List implementation returned by subList does not implement the remove operation, so you will get a java.lang.UnsupportedOperationException.

You should create sub as an ArrayList instead:

ArrayList<Eval> sub = new ArrayList<Eval>(ev.subList(1, 4));