How to use ArrayList in Scala

ArrayList in Scala

In this example, we will show simple program about, How to use ArrayList in Scala. The example program has been tested and shared in the same post.

Example 1 – Adding String Object to ArrayList

package com.dineshkrish.scala
import java.util.ArrayList
object Example1 {
def main(args: Array[String]): Unit = {
// creating array list object
var list = new ArrayList[String]();
// adding elements
for (a <- 65 to 90) {
list.add("" + (a.asInstanceOf[Char]) + ""); // type casting int to char
}
// printing the list
println(list);
}
}

Output

[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]

Example 2 - Adding Custom Object to ArrayList

package com.dineshkrish.scala
import java.util.ArrayList
object Example2 {
def main(args: Array[String]): Unit = {
// creating array list object
var list = new ArrayList[Employee]();
// employee object 1
var emp1 = new Employee(101, "Dinesh");
// employee object 2
var emp2 = new Employee(102, "Krishnan");
// employee object 3
var emp3 = new Employee(103, "John");
// adding the employee objects
list.add(emp1);
list.add(emp2);
list.add(emp3);
// looping through list object
for (a <- 0 to (list.size() - 1)) {
/// printing object from list
println(list.get(a));
}
}
}

Employee Class (Employee.scala)

package com.dineshkrish.scala
class Employee(empId: Int, empName: String) {
def getEmpId() : Int = {
return empId;
}
def getEmpName() : String = {
return empName;
}
override def toString() : String = {
return "[empId : "+empId+", empName : "+empName+"]";
}
}

Output

[empId : 101, empName : Dinesh]
[empId : 102, empName : Krishnan]
[empId : 103, empName : John]

References

1. Overriding toString() method

Tags:

No Responses

Leave a Reply

Your email address will not be published.