-1
package MiscellaneousProjects

import java.util.*

class Numbers(val numbers: Int){
}

fun ClosedRange<Int>.random() = Random().nextInt((endInclusive + 1) - start) +  start // Function to randomly generate a number

fun main(args: Array<String>) {
    var list = arrayListOf<Numbers>()
    for(i in 1..10){
        val random = Random()
        list.add(Numbers((0..100).random())) // Adds the numbers to an array
    }

    var sortedList = list.sortedWith(compareBy({ it.numbers })) // Sorts the elements from least to greatest

    for(element in sortedList){
        println(element.numbers) // Prints the individual entries
    }

    println(sortedList)

}

The following piece of code picks a number from 0 to 100 and adds it to an array.

I am sorting the numbers from greatest to least using sortedWith and compareBy functions. However, when I print "sortedList," the following types of entries are seen: "MiscellaneousProjects.Numbers@30f39991, MiscellaneousProjects.Numbers@452b3a41."

However, whenever I print the individual elements in the array, it outputs the correct numbers.

Can someone tell me the error in my code?

2 Answers2

2

Either use a data class for Numbers (which basically has a built-in toString() that will probably suffice your needs already) or just override toString() yourself in the Numbers class to return the numbers, e.g.

override fun toString() = numbers.toString()
Roland
  • 22,259
  • 4
  • 57
  • 84
0

The issue is that you're relying on the default implementation of toString for your Numbers class, which is inherited from Object and prints what you see (i.e., <class_name>@<hash_code>, as you can find here).

To print something more meaningful you can override the toString method (or fun in Kotlin) to return the String you're expecting

user2340612
  • 10,053
  • 4
  • 41
  • 66