java.lang.ClassCastException: jdk.nashorn.internal.objects.NativeArray cannot be cast to java.lang.Comparable

StackOverflow https://stackoverflow.com/questions/23100392

  •  04-07-2023
  •  | 
  •  

Question

While running JavaScript with Nashorn

var jsArray = [7,4,1,8,3,2]; 
var list = java.util.Arrays.asList(jsArray);
java.util.Collections.sort(list);
list.forEach(function(el) { print(el) } ); 

i got

Exception in thread "main" java.lang.ClassCastException: jdk.nashorn.internal.objects.NativeArray cannot be cast to java.lang.Comparable
at java.util.Collections.sort(Collections.java:170)

So is the way to use Java Collections in JavaScript?

UPDATE:

Thanks to Attila, not both JS and JJS script produce the same output

var jsArray = [1,2,3,4]; 
jsArray.forEach(function(el) { print(el) } ); 


var jsArray = [1,2,3,4];
//var list = java.util.Arrays.asList(jsArray);
var list = Java.to(jsArray, Java.type('java.util.List'))
list.forEach(function(el) { print(el) } ); 
Was it helpful?

Solution

Using java.util.Arrays.asList will create an array with a single element being the JS array. JS arrays aren't Java arrays...

Instead of java.util.Arrays.asList, use Java.to(jsArray, Java.type('java.util.List')). The resulting list will be backed by the JS array, so changes to one will be reflected by the other. You can also convert the JS array to a Java array with just Java.to(jsArray) (which is equivalent to Java.to(jsArray, Java.type('java.lang.Object[]'). So if you want to go through the array conversion step, you can use java.util.Arrays.asList(Java.to(jsArray));.

In general, Nashorn will convert JS arrays to Java arrays automatically in most cases where the Java method signature specifies an array parameter, so you don't have to use Java.to() explicitly a lot. Arrays.asList(T...) is unfortunately a vararg method, so there's some ambiguity as to how to handle the argument.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top