0

I'm trying to get a segment from an arrayList by index and by keeping a reference to the original arrayList, but when I use subList it returns me a list. I want to keep my arrayList structure. For that, a made a cast ( Error: java.util.ArrayList$SubList cannot be cast to java.util.ArrayList)

Source code:

ArrayList< Integer > TAB = new ArrayList< Integer >();
ArrayList< Integer > TAB_Segment = new ArrayList< Integer >();

TAB.add(new Integer( 0 ));
TAB.add(new Integer( 1 ));
TAB.add(new Integer( 2 ));
TAB.add(new Integer( 4 ));
TAB.add(new Integer( 5 ));

TAB_Segment = TAB.subList(0,2); // error
TAB_Segment = (ArrayList<Integer>) TAB.subList(0,2); // error java.util.ArrayList$SubList cannot be cast to java.util.ArrayList)

To preserve my arrayList structure, I find removeRange. Sadly this function doesn't return anything and it makes the inverse of what I really need. So, is there a way to attend my goal?

David Edgar
  • 477
  • 8
  • 23
  • the method returns `List`. Is there any reason you can't use that? It's a view into the original `ArrayList`. Alternatively, make a new `ArrayList` from the sublist. – pvg Jul 01 '16 at 18:43

1 Answers1

0

You are programming to the class ArrayList and not the interface List... that is the reason of the hole bad desing causing the issues in the code... because you need to cast the List to ArrayList changing this:

ArrayList< Integer > TAB = new ArrayList< Integer >();
ArrayList< Integer > TAB_Segment = new ArrayList< Integer >();

for this

List<Integer> TAB = new ArrayList<Integer >();
List<Integer> TAB_Segment = new ArrayList<Integer >();

will resolve the hole problem...

Example:

public static void main(String[] args) {
List<Integer> TAB = new ArrayList<>();
List<Integer> TAB_Segment = new ArrayList<>();

TAB.add(new Integer(0));
TAB.add(new Integer(1));
TAB.add(new Integer(2));
TAB.add(new Integer(4));
TAB.add(new Integer(5));

TAB_Segment = TAB.subList(0, 2); // error
TAB_Segment = TAB.subList(0, 2); // error java.uti

}
Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97