prepare123
prepare123

Reputation: 165

how to add Array index value in Kotlin?

first, I create empty Array(Kotlin) instance in companion object.

 companion object {
        var strarray: Array<String> = arrayOf()
        var objectarray: LinkedHashMap<Int, List<Any>> = LinkedHashMap<Int, List<Any>>()
    }

and I expected that I use empty array instance when read textString from CSV File.

 fun csvFileToString():String {

    val inputStream = File(Paths.get("").toAbsolutePath().toString()
            .plus("/src/main/SampleCSVFile_2kb.csv")).inputStream()
    val reader = inputStream.bufferedReader()
    var iterator = reader.lineSequence().iterator()
    var index:Int = 1;

    while (iterator.hasNext()){
        var lineText:String = iterator.next()
       strarray.set(index, lineText)
       index++
    }

    return ""
}

but when I run that source code

a.csvFileToString()
println(CsvParser.strarray)

occured exception

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 
strarray.set(index, lineText) <<<<<<<<< because of this line

can I use Array(from kotlin collection) like ArrayList(from java collection)?

Upvotes: 3

Views: 7390

Answers (3)

The MJ
The MJ

Reputation: 473

You can add a new item to an array using +=, for example: item += item

private var songs: Array<String> = arrayOf()
   fun add(input: String) {
        songs += input
    }

Upvotes: 5

Eugen Pechanec
Eugen Pechanec

Reputation: 38223

  • arrayOf gives you an array. Arrays have fixed length even in Java.

  • listOf gives you an immutable list. You cannot add or remove items in this list.

  • What you're looking for is mutableListOf<String>.

In your current approach, reusing a member property, don't forget to clear the list before every use.

Your code can be further simplified (and improved) like so:

out.clear()
inputStream.bufferedReader().use { reader -> // Use takes care of closing reader.
    val lines = reader.lineSequence()
    out.addAll(lines) // MutableList can add all from sequence.
}

Now imagine you wanted to consume the output list but needed to parse another file at the same time.

Consider working towards a pure function (no side effects, for now no accessing member properties) and simplifying it even further:

fun csvFileToString(): String { // Now method returns something useful.
    val inputStream = File(Paths.get("").toAbsolutePath().toString()
            .plus("/src/main/SampleCSVFile_2kb.csv")).inputStream()

    inputStream.bufferedReader().use {
        return it.lineSequence().joinToString("\n")
    }
}

In this case we can totally skip the lists and arrays and just read the text:

inputStream.bufferedReader().use {
    return it.readText()
}

I'm assuming that's what you wanted in the first place.

Kotlin has a lot of useful extension functions built-in. Look for them first.

Upvotes: 2

pwolaq
pwolaq

Reputation: 6381

Size of Array is defined at its creation and cannot be modified - in your example it equals 0.

If you want to create Array with dynamic size you should use ArrayList.

Upvotes: 4

Related Questions