Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy getAt() vs get()

Tags:

groovy

Consider the list :
def list = [1, 2, 3]
If I use
list.getAt(0)
or
list.get(0)
Both will give the same output.
But is there any difference between getAt() and get()?

like image 518
rvd Avatar asked Mar 25 '14 07:03

rvd


People also ask

How to use each () method in Groovy?

The each () method accepts a closure and is very similar to the foreach () method in Java. Groovy passes an implicit parameter it which corresponds to the current element in each iteration: def list = [ 1, "App", 3, 4 ] list.each {println it * 2 }

How to compare two lists in Groovy?

Groovy uses the “==” operator to compare the elements in two lists for equality. Continuing with the previous example, on comparing cloneList with arrlist the result is true: Now, let's look at how to perform some common operations on lists. 3. Retrieving Items from a List We can get an item from a list using the literal syntax such as:

How to get the property of a special object in Groovy?

According to the document of groovy, groovy may use "getProperty" method to get the property of a object. So when I want to change the behavier of getting property on the special object, I use a category class to override the "getProperty" method. However, it does not work.

How do you iterate over a list in Groovy?

Lets start by looking at the two methods for iterating over a list. The each() method accepts a closure and is very similar to the foreach() method in Java. Groovy passes an implicit parameter it which corresponds to the current element in each iteration: def list = [1,"App",3,4] list.each {println it * 2}


2 Answers

The documentation explains it:

Support the subscript operator for a List.

def list = [2, "a", 5.3]
assert list[1] == "a"

So there's no difference, but getAt() is the method allowing Groovy code to use list[1] instead of list.get(1)

See http://groovy.codehaus.org/Operator+Overloading for how operator overloading works.

like image 50
JB Nizet Avatar answered Oct 10 '22 04:10

JB Nizet


The documentation doesn't explain this well, but what actually seems to be the difference in my testing is that getAt(i) will return null when referencing indexes not actually in the list, while the get(i) method will throw an IndexOutOfBoundsException when an index not in the list is passed in, just as plain old Java would.

like image 24
gstephas Avatar answered Oct 10 '22 04:10

gstephas