Skip to content
This repository has been archived by the owner on Aug 5, 2021. It is now read-only.

Task i.10 expects list in descending order instead of ascending #108

Open
beheist opened this issue Sep 21, 2017 · 2 comments
Open

Task i.10 expects list in descending order instead of ascending #108

beheist opened this issue Sep 21, 2017 · 2 comments

Comments

@beheist
Copy link

beheist commented Sep 21, 2017

According to the java doc, the java.util.Comparator should do the follwing:

Compares its two arguments for order.  Returns a negative integer,
zero, or a positive integer as the first argument is less than, equal
to, or greater than the second.

The current suggested resolution is:

Collections.sort(arrayList, object : Comparator<Int> {
    override fun compare(x: Int, y: Int) = y - x
})

which does the opposite - it returns a positive number if the first argument is less than the second, and a negative if the first argument is greater than the second.
I suggest changing the solution to:

Collections.sort(arrayList, object : Comparator<Int> {
    override fun compare(x: Int, y: Int) = x - y
})

and the test to:

class N10ObjectExpressionsKtTest {
    @Test fun testSort() {
        assertEquals(listOf(1, 2, 5), task10())
    }
}
@daj
Copy link

daj commented Dec 24, 2017

I initially thought the same thing as I wanted my compare function to match the definition in the Comparator interface.

However, the problem TODO does specifically state to sort in decending order:

Add an object expression that provides a comparator to sort a list in a descending order using 'java.util.Collections' class.

One way to maintain the true contract of compare, but without modifying the problem is to use the reversed method:

class MyComparator : Comparator<Int> {
    override fun compare(x: Int, y: Int) = x - y
}

fun task10(): List<Int> {
    val arrayList = arrayListOf(1, 5, 2)
    Collections.sort(arrayList, MyComparator().reversed())
    return arrayList
}

@trietbui85
Copy link

Hi, as I know (not sure just from Kotlin 1.1), all arguments of compare() method are nullable. It means that method should be fun compare(x: Int?, y: Int?): Int. Thus, we should check these arguments for nullability first.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants