5

I'm trying to initialize a HashMap using rJava with type <String, Double> but do not understand how to accomplish this using the rJava interface. I am basically looking for the equivalent of

HashMap<String, Double> x = new HashMap<String, Double>();

but using rJava instead. I can easily produce a HashMap<String, String> as the following example shows, but naturally cannot populate the values with doubles (which is what I want to achieve).

library(rJava)
.jinit()

# this works but gives me a <String, String> hashmap
x <- .jnew("java/util/HashMap")
.jrcall(x, "put", "a", "1")
x

#> [1] "Java-Object{{a=1}}"

# failing example of what I'd like to do
.jrcall(x, "put", "b", 2)

#> Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl,  : 
#>   java.lang.NoSuchMethodException: No suitable method for the given parameters

I have tried to string together combinations using .jcall() in several variations on the following theme:

.jcall("java/util/HashMap",
       "Ljava/util/HashMap;[Ljava/lang/String;Ljava/lang/Double;",
       "<init>")
#> Error in .jcall("java/util/HashMap", "Ljava/util/HashMap; 
#>   [Ljava/lang/String;Ljava/lang/Double;",  : 
#>   method <init> with signature ()Ljava/util/HashMap; 
#>   [Ljava/lang/String;Ljava/lang/Double; not found

But nothing has so far succeeded.

3
  • How exactly does the .jrcall(y, "put", "b", 2) fail? What is the error message? Commented Apr 9, 2018 at 11:29
  • I've updated the question with this info @Thilo Commented Apr 9, 2018 at 11:49
  • Not familiar with RJava, but maybe it cannot find the method because it does not automatically box the primitive number argument. Can you try .jrcall(y, "put", "b", twoAsJavaDoubleInstance) (no idea how to get the latter from R, though, in Java it would be Double.valueOf(2)))? Commented Apr 10, 2018 at 6:50

1 Answer 1

4
+50

You can create a Double object with .jnew("java/lang/Double", value):

library(rJava)
.jinit()

x <- .jnew("java/util/HashMap")
y <- .jnew("java/lang/Double", 3.14)
.jrcall(x, "put", "a", y)

x
[1] "Java-Object{{a=3.14}}"
Sign up to request clarification or add additional context in comments.

Comments

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.