1

I'm trying to convert Scala List to a Java ArrayList.

import collection.JavaConverters._

val list: java.util.ArrayList[String] = List("hello", "world").asJava

It doesn't seem to be working.

How can I do this?

3 Answers 3

3

The asJava function returns an object that implements the java.util.List interface. This object is backed by your original list. You can find the documentation for this here (check the seqAsJavaList function):

http://www.scala-lang.org/api/2.12.0/scala/collection/JavaConverters$.html

If you want an instance of java.util.ArrayList, you can create one using the constructor that takes a Collection. Like this:

import java.util.ArrayList
val list = new ArrayList(List("hello", "world").asJava)
Sign up to request clarification or add additional context in comments.

Comments

1

asJava return a java.util.List, not an ArrayList You can convert to an ArrayList using the constructor ArrayList(c: java.util.Collection[_ <: String)

val list: java.util.ArrayList[String] = new java.util.ArrayList(List("hello", "world").asJava)

Comments

-2

Try this:

  val list: java.util.ArrayList[String] = new java.util.ArrayList[String]() 
    list.addAll(List("hello", "world").asJava)

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.