Groovy Tip 5: Arrays

Source: Internet
Author: User
Tags arrays

The definition of an array and the initial value of an assignment

In the groovy language, arrays are defined in the same way as in the Java language.

def a = new String[4]
  
  def nums = newint[10]
  
def objs = new Object[3]

And then the assignment is the same:

a[0] = 'a'
  a[1] = 'b'
  a[2] = 'c'
a[3] = 'd'

The difference is in assigning an initial value when the array is defined.

In the Java language, this is defined as an array of strings:

String[] strs = new String[]{'a','b','c','d'};

In the groovy language, it is necessary to define a string array:

def strs = ['a','b','c','d'] as String[]

Second, the array of traversal

In the groovy language, there are many ways to iterate an array, often using each method:

a.each{
    println it
}

Of course, you can also use the enhanced for loop:

for(it in a)
  {
    println it
}

You can also use the following traversal method:

(0..<a.length).each{
    println a[it]
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.