Consider the list :def list = [1, 2, 3]
If I uselist.getAt(0)
orlist.get(0)
Both will give the same output.
But is there any difference between getAt() and get()?
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 }
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:
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.
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}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With