Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList is not sorted by groovy Arrays.sort()

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
like image 342
yohabe Avatar asked Feb 11 '26 16:02

yohabe


2 Answers

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]
like image 185
Danilo Avatar answered Feb 17 '26 13:02

Danilo


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]
like image 31
Ken Geis Avatar answered Feb 17 '26 15:02

Ken Geis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!