JavaでArrayListのサブリストを取得する
Java で ArrayList の一部を取得するには、メソッドsubList()>List subList(int fromIndex, int toIndex)
fromIndex が含まれ、toIndex excludes ( [fromIndex, toIndex[ ) です。このメソッドはlist型のオブジェクトを返すので、サブリストを別のArrayListに格納するには、ListからこのArrayListを作成する必要があります。new ArrayList(input.subList(fromIndex, toIndex)) です。一方、結果のサブリストをリストに格納する場合は、例のように問題ありません.
import java.util.ArrayList;Runtime:
import java.util.List;
public class ArrayListSublist {
public static void main(String[] args) {
// ArrayList を作成します<文字列>
ArrayList<文字列>aList = new ArrayListです<文字列>();
//ArrayListに文字列を追加
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
System.out.println("ArrayList");
for(String e:aList)
System.out.println(e);
リストリスト = aList.subList(1, 4);
System.out.println("ArrayList ");
for(int i=0; i< list.size();i++)
System.out.println(list.get(i));
}
}
ArrayList
1
2
3
4
5
ArrayList
2
3
4
Remaque:
subList() メソッドは例外 IndexOutOfBoundsException 指定したインデックスが 0 未満またはサイズを超える場合.
IllegalArgumentException fromIndex が toIndex より大きい場合、つまりfromIndex >toIndexです。
subList() メソッドは例外 IndexOutOfBoundsException 指定したインデックスが 0 未満またはサイズを超える場合.
IllegalArgumentException fromIndex が toIndex より大きい場合、つまりfromIndex >toIndexです。