1

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) } ); 

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

How can I convert other classes? Java.to(myJsObject, Java.type('com.xyz.MyClass')) doesn't work and I get Unsupported Java.to target type com.xyz.MyClass

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.