VolodymyrH
VolodymyrH

Reputation: 2019

List or array is always empty in Kotlin

I'm trying to write simple Stack on Kotlin, but all data containers are always throws ArrayIndexOutOfBoundsException. I can't find out what can cause this problem:

class StackX(size: Int) {
    private var maxSize: Int = size
    private var stackArray: Array<Long> = arrayOf(maxSize.toLong())
    private var top = -1

    fun push(data: Long) {
        stackArray[++top] = data
    }

    fun pop() : Long {
        return stackArray[top--]
    }

    fun peek() : Long {
        return stackArray[top]
    }

    fun isEmpty() : Boolean {
        return (top == -1)
    }

    fun isFull() : Boolean {
        return (top == maxSize -1)
    }
}

Could you please explain me the right patter of arrays declaration in this case? I want just this:

int a[] = new int[10];

P.S. It's test code, I even doesn't call pop. It throws on push. I'm just trying to understand what's wrong with declaration.

Upvotes: 1

Views: 2259

Answers (2)

Alex Romanov
Alex Romanov

Reputation: 11963

The problem is in your push() method.

private var stackArray: ArrayList<Long> = arrayListOf() // size = 0
private var top = -1

fun push(data: Long) {
    stackArray[++top] = data // top = 0
}

What you're trying to do is to get the 0th element of an empty list.

Possible fix:

fun push(data: Long) {
    stackArray.add(data)
    ++top
}

Updated.

  • Creating an int array of the specified size:

    int[] a = new int[10]; // Java
    val a = IntArray(10)   // Kotlin
    

    All elements are initialized to zero.

  • Creating a DataItem array:

    DataItem[] b = new DataItem[10];   // Java
    val b = arrayOfNulls<DataItem>(10) // Kotlin
    

    All elements are initialized to null.

Upvotes: 1

djm.im
djm.im

Reputation: 3323

This line is the problem private var stackArray: ArrayList<Long> = arrayListOf().
It creates an array which length is 0.

Perhaps, you want something like this val stackArray: LongArray = LongArray(size).

Upvotes: 1

Related Questions