Arrays.sort() in groovy doesn't work. Why??
groovy program:
foo = [3,2,1,9]
Arrays.sort(foo)
println foo.getClass()
println foo
result:
class java.util.ArrayList
[3, 2, 1, 9]
version:
$ groovy --version
Groovy Version: 2.4.4 JVM: 1.7.0_80 Vendor: Oracle Corporation OS: Mac OS X
I thought this is caused by java.util.ArrayList. so I tried to add "type"(see below), it's ok(I can get sorted result). But I cannot understand these groovy behavior...
groovy(this will be sorted):
int[] foo2 = [3,2,1,9]
Arrays.sort(foo2)
println foo2.getClass()
println foo2
As pointed out in other answers, Arrays works on Arrays. Array and ArrayList are very different data structures, the main difference being the former being a fixed-length structure and the latter a variable-length data.
What you are looking for in your code is to substitute Arrays.sort(foo) with Collections.sort(foo).
However, with Groovy you can simply invoke the sort() method on your ArrayList object. Note that sort is also a closure, so you can implement a custom sorting algorithm directly on your object:
foo = [3,2,1,9]
println foo.getClass()
println foo //[3,2,1,9]
Collections.sort(foo)
println foo //[1,2,3,9]
println foo.sort() //[1, 2, 3, 9]
println foo.sort{a,b-> a-b } //[1, 2, 3, 9]
println foo.sort{a,b-> b-a } //[9, 3, 2, 1]
Arrays.sort() expects arrays. Groovy interprets passing an object in as one argument in a varargs-style list of arguments. You can see this here:
def test(Object[] a) {
println a[0]
}
test(foo)
outputs
[3, 2, 1, 9]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With