Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexOutOfBoundException(Java)

Tags:

java

I get an error:

Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

from the code below which I think is perfectly fine!! Any guidance will be warmly appreciated

for (int i = 0; i < allVacantRooms.size(); i++) {       
  String allavail=allVacantRooms.get(i).getName();
  System.out.println(allavail);
  for (int j = 0; j < deductableRooms.size(); j++) {
    String alldeduc=deductableRooms.get(j).getReservation()
                        .getReservedRooms().get(j).getRoom();
    System.out.println("allDeduc::"+alldeduc);
  }
}
like image 402
Manish Karki Avatar asked Jun 30 '26 15:06

Manish Karki


2 Answers

Seems like the problem is with this line:

String alldeduc = deductableRooms.get(j).getReservation().getReservedRooms().get(j).getRoom();

The get() on ReservedRooms is dangerous!

It seems like you have 2 deductableRooms but only 1 reservedRoom in deductableRoom.get(1).

enter image description here

Maybe you need a third loop over your reservedRooms.
Depends on what you are actually trying to do.
Right now you are printing the ReservedRoom as deductRoom which seems strange to me

like image 165
JDurstberger Avatar answered Jul 03 '26 05:07

JDurstberger


You are blindly using the same index on reservationRooms as you are on the reservation they belong to. You should iterate over the room in a separate loop.

Also, your code style is poor; prefer a "for each" loop when you don't need the index (as here).

Also also, the outer loop is not related to the inner loop; they should be separate loops.

Try something like:

for (ReservedRoom room : allVacantRooms) {
    System.out.println(room.getName());
}
for (ReservedRoom room : deductableRooms) {
    for (ReservedRoom reservedRoom : room.getReservation().getReservedRooms()) {
        System.out.println("allDeduc::" + reservedRoom.getName());
    }
}
like image 20
Bohemian Avatar answered Jul 03 '26 05:07

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!