Program to print Java List in Scala
A java list can be returned from a Scala program by writing a user defined method of Java in Scala. Here, we don’t even need to import any Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples.
Example:1#
Scala
object GfG
{
def main(args : Array[String])
{
def result = {
val list = new java.util.ArrayList[Int]()
list.add( 11 )
list.add( 12 )
println(list)
}
val list = result
}
}
|
Time Complexity: O(1) because the only operation being performed is the creation of a new Java ArrayList and adding two elements to it, both of which are constant-time operations
Auxiliary Space: O(1) because the only variables being used are a few integers and a reference to the Java ArrayList, which are all constant in size regardless of the input size.
Therefore, a list is returned from a Java method. Here, we don’t need to import any object of Scala. In the above program a Java method is written in Scala program. Where this method adds the elements of the list to the stated list one after another and then prints the results. Example:2#
Scala
object GfG
{
def main(args : Array[String])
{
def result = {
val list = new java.util.ArrayList[Int]()
list.add( 11 )
list.add( 12 )
list.add( 17 )
println(list)
}
val list = result
}
}
|
It is same as above example but here one more element is added in the stated list.
Time Complexity: O(1), as it only performs a few constant-time operations such as creating an ArrayList object and adding a few elements to it.
Auxiliary Space: O(1), as it does not use any additional data structures and only creates a single java ArrayList object.
Last Updated :
05 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...