Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use subList()

Tags:

java

I have a JSF page which displays list of Glassfish log files. I use lazy loading for pagination. I keep the list of the log files names into Java List.

private List<directoryListObj> dataList = new ArrayList<>();  dataList = dataList.subList(firstRow, lastRow); 

And here is the problem. For example I have 35 files into the directory. When I do this

dataList = dataList.subList(5, 15); 

It works fine. But when I do this:

dataList = dataList.subList(30, 38); 

I get error wrong index because I want to get index outside of the List. How I can for example return List elements from 30 to 35? I want if I want to get index from 30 to 40 but if there only 35 indexes to get only 5.

like image 940
user1285928 Avatar asked Aug 23 '12 20:08

user1285928


People also ask

What is the use of subList in Java?

The subList() method of java. util. ArrayList class is used to return a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.)

What is the way to get subList from an ArrayList?

ArrayList. subList() method. This method takes two parameters i.e. the start index for the sub-list(inclusive) and the end index for the sub-list(exclusive) from the required ArrayList. If the start index and the end index are the same, then an empty sub-list is returned.

Does subList create a new list?

subList is a method in the List interface that lets you create a new list from a portion of an existing list. However, this newly created list is only a view with a reference to the original list.


2 Answers

Using subList(30, 38); will fail because max index 38 is not available in list, so its not possible.

Only way may be before asking for the sublist, you explicitly determine the max index using list size() method.

for example, check size, which returns 35, so call sublist(30, size());

OR

COPIED FROM pb2q comment

dataList = dataList.subList(30, 38 > dataList.size() ? dataList.size() : 38); 
like image 96
kosa Avatar answered Oct 23 '22 12:10

kosa


I've implemented and tested this one; it should cover most bases:

public static <T> List<T> safeSubList(List<T> list, int fromIndex, int toIndex) {     int size = list.size();     if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) {         return Collections.emptyList();     }      fromIndex = Math.max(0, fromIndex);     toIndex = Math.min(size, toIndex);      return list.subList(fromIndex, toIndex); } 
like image 39
Haroldo_OK Avatar answered Oct 23 '22 10:10

Haroldo_OK