Using List
Creating an instance of java.util.ArrayList is easier in Groovy than in Java. We don’t have to use new or specify the class name. We can simply list the initial values we want in the List, as shown here:
WorkingWithCollections/CreatingArrayList.groovy | |
| lst = [1, 3, 4, 1, 8, 9, 2, 6] |
| println lst |
| println lst.getClass().name |
Let’s look at the ArrayList’s contents and its type, as reported by Groovy:
| [1, 3, 4, 1, 8, 9, 2, 6] |
| java.util.ArrayList |
When we declare a list in Groovy, the reference lst refers to an instance of java.util.ArrayList, as we can see from the previous output.
We can fetch the elements of the List by using the [] operator, as shown in the next example:
WorkingWithCollections/CreatingArrayList.groovy | |
| println ... |
Get Programming Groovy 2 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.