How to stop reading the list-eh?

Hello,
please help can't figure out how to stop reading from a List.
public String NumberOfRecords() {
 String n1 = tableCity.get(n2);
 n2++; 
 return n1; 
 }

tableCity - List is populated from the database.
You drive we the data into the table. Table dynamic.
<div id="list">
<f:view>
 <h:form> 
 <p:datatable var="directory" value="#{dataDB.tableCity}" style="margin-bottom:280px; font-size: 12px">
 <!-- <p:ajax event="rowEdit" listener="#{dtEditView.onRowEdit}" update=":form:msgs" />
 <p:ajax event="rowEditCancel" listener="#{dtEditView.onRowCancel}" update=":form:msgs" />
-->
 <c:foreach items="#{dataDB.columns}" var="obj">
 <p:column headertext="#{dataDB.NumberOfColumn()}"> 
 <h:outputtext value="#{dataDB.NumberOfRecords()}">
</h:outputtext></p:column>
</c:foreach>
</p:datatable>
</h:form>
</f:view>
 </div>
Realize that the brain needs some kind of limiter to deliver or foreach, but can not think of what.
Error Index 304, Size:304 (sheet 304 of record, by the way, if output System.out.print(n1) - all entry in the log reads and then error)
The part of the log:

Severe: Error Rendering View[/directory.xhtml]
javax.el.ELException: /directory.xhtml @63,85 value="#{dataDB.NumberOfRecords()}": java.lang.IndexOutOfBoundsException: Index: 304, Size: 304
.......................
FATAL: JSF1073: javax.el.ELException caught during processing of RENDER_RESPONSE 6 : UIComponent-ClientId=, Message=/directory.xhtml @63,85 value="#{dataDB.NumberOfRecords()}": java.lang.IndexOutOfBoundsException: Index: 304, Size: 304
FATAL: /directory.xhtml @63,85 value="#{dataDB.NumberOfRecords()}": java.lang.IndexOutOfBoundsException: Index: 304, Size: 304
javax.el.ELException: /directory.xhtml @63,85 value="#{dataDB.NumberOfRecords()}": java.lang.IndexOutOfBoundsException: Index: 304, Size: 304
....................
August 23rd 19 at 11:35
1 answer
August 23rd 19 at 11:37
The recording sheet 304, but the index of the last entry 303. Therefore, I get the error "IndexOutOfBoundsException: Index: 304, Size: 304".
Need before reading from a worksheet to check whether the index exceeds the size of this collection. For example:

if(n2 < tableCity.size()) {
 String n1 = tableCity.get(n2);
 n2++; 
 return n1; 
}
It does not work if I return in the condition do, swears that there is no return - rudolph commented on August 23rd 19 at 11:40
Only find the decision to limit the table. It's just a sheet of 304 records, for example. 76 rows by 4 columns. So I did a number of records/number of columns. So it works, but it's probably not very nice and professional - rudolph commented on August 23rd 19 at 11:43
Correctly swears ) because the Method has something to return. In General, to iterate over collections, you should not use indexes. You can, but not always necessary. Easier to iterate over them using loop: for(String record : tableCity) { ... } - rossie_Stokes commented on August 23rd 19 at 11:46

Find more questions by tags HTMLJava