kotlin,从arrayObject创建一个arraylist

时间:2018-11-15 10:09:41

标签: android arrays arraylist kotlin

尝试使用以下代码的ArrayList从我的对象中创建一个Arraylist。 这是我的代码:-

       var i = 1.0
    var list: ArrayList<Any> = ArrayList()
    while (i <= n) {
        intPerMonth = P * R
        P = P - (e - intPerMonth)
        Log.e("TAG", "Month -> " + i.toInt())
        Log.e("TAG", "Interest per month -> " + Math.round(intPerMonth))
        Log.e("TAG", "Principal per month -> " + Math.round(e - intPerMonth))
        Log.e("TAG", "Balance Principal -> " + Math.round(P))
        Log.e("TAG", "***************************")

        list = arrayListOf(
            i.toInt(),
            Math.round(intPerMonth),
            Math.round(e - intPerMonth),
            Math.round(e - intPerMonth),
            Math.round(P)
        )
        i++
        Log.e("myArray", list.toString()) // this list.toString() is my output

    }

该程序的输出为

E/myArray: [1, 10, 79, 79, 921] E/myArray: [2, 9, 80, 80, 842] E/myArray: [3, 8, 80, 80, 761]

但是我想要这种类型的列表:-

[(1,10,79,79,921),(2,9,80,80,842),(3,8,80,80,761)]

1 个答案:

答案 0 :(得分:0)

因此,您似乎想要一个列表列表?尝试在每次迭代中创建一个内部列表,然后将其添加到列表中,如下所示:

var i = 1.0
var list: ArrayList<Any> = ArrayList()
while (i <= n) {
    intPerMonth = P * R
    P = P - (e - intPerMonth)
    Log.e("TAG", "Month -> " + i.toInt())
    Log.e("TAG", "Interest per month -> " + Math.round(intPerMonth))
    Log.e("TAG", "Principal per month -> " + Math.round(e - intPerMonth))
    Log.e("TAG", "Balance Principal -> " + Math.round(P))
    Log.e("TAG", "***************************")

    var innerList = arrayListOf( // create a different list here
        i.toInt(),
        Math.round(intPerMonth),
        Math.round(e - intPerMonth),
        Math.round(e - intPerMonth),
        Math.round(P)
    )
    list.add(innerList) // add the inner list to your list
    i++
}
Log.e("myArray", list.toString()) // this prints the new list of lists