MattMcCann
MattMcCann

Reputation: 40

Kotlin: java.lang.IndexOutOfBoundsException: Index: 3, Size: 3

I am looping through an Array List and am getting thrown this error

java.lang.IndexOutOfBoundsException: Index: 3, Size: 3

Here is the Code

for(i in chatMessages.indices) {
    if(i < chatMessages.size){
   if(chatMessages[i] == "To" && chatMessages[i+1] != "To") {
     lastItem = true
 }}
 }

The Error is occurring with the following condition

chatMessages[i] == "To" && chatMessages[i+1] != "To"

Here is the array declaration

var chatMessages = arrayListOf<String>()

Why is my condition i < chatMessages.size not working?

Any help would be great

~ Matthew M

Upvotes: 0

Views: 2160

Answers (1)

sidgate
sidgate

Reputation: 15234

Even if you check for i < chatMessages.size, you are trying to access [i + 1]th element that is not present. Change the if statement to size-1 or should be less than the lastIndex

for (i in chatMessages.indices) {
  if (i < chatMessages.lastIndex) {
    if (chatMessages[i] == "To" && chatMessages[i + 1] != "To") {
      lastItem = true
    }
  }
}

Better solution with immutable variable and functional approach

val lastItem = chatMessages.zipWithNext()
    .any { it.first == "To" && it.second != "To" }

Upvotes: 1

Related Questions