Java Examples: Ragged Array

Updated on January 29, 2018
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 Yrs. I like playing video games & reading books.

1. Introduction

In java, "Ragged Array" is an “Array of Array”. This means one can create an array in such a way that each element of the array is a reference to another array of same type. For example, a two-dimensional array of 3 x 2 refers three rows and two columns (i.e.) each row has two columns. We call this as “Rectangular Array”. In case of a Ragged Array, the number of columns may not be fixed.

Note that "Jagged Array" and "Ragged Array" and "Irregular Dimensional Array" all refers the same.

2. Declaring a Ragged Array

The below code (Listing 1.) declares a ragged array:

Listing 1

//Snippet 01: Declare an 2D Irregular Array
double[][] ir_array = new double [3][];

Here, ir_array is a ragged array and the dimension on the right-hand side [3][] specifies one dimension as fixed and another dimension as unknown. Here, in the above code we can call ir_array as One- dimensional array of double array. Like this one can create “Multi-dimensional Ragged Array”.

3. Setting the Array References

Now, it is time to allocate space for three array of type double and setting its reference in the first dimension. Below code (Listing 2) shows setting up the ragged dimension:

Listing 2.

//Snippet 02: Now declare three arrays
ir_array[0] = new double[5];
ir_array[1] = new double[3];
ir_array[2] = new double[2];

Here, we created three arrays to store double and the array size is 5,3,2. Each array is stacked in the array ir_array. For Example, the first double array of size 5 is stored in the first slot of ir_array and the same way the second array of size 3 is stored in the second slot of the ir_array and so on.

In the above code we had setup our ragged array. The three slots (Ley say this as row) forms a three row and each row say represents an array. For Example, ir_array[2] is third row and represents an array of size 2 which represents the columns for it. OK, let us populate this array now.

4. Populating the Ragged Array

Have a look at the below code which populates the ragged array:

Listing 3.

//Snippet 03: Initialize the arrays
for (int i = 0; i < 5; i++) {
    ir_array[0][i] = (i + 1) * 10;
}

for (int i = 0; i < 3; i++) {
    ir_array[1][i] = (i + 1) * 5;
}

for (int i = 0; i < 2; i++) {
    ir_array[2][i] = (i + 1) * 2;
}

In the above code, the first array of double is filled with the value which is multiples of 10 and the five element values are 10,20,30,40,50. The second array of double is filled with the values which is multiple of 5. The third array is filled with the value which is multiple of 2. After populating the array, the array will look as shown below:

Java Ragged Array
Java Ragged Array | Source

5. Picking Ragged Array Element

Once the ragged array is ready, the elements value can be picked just like a regular array. Here in our example, we setup a ragged array with two dimensions and so to pick an element from this array we need to locate the cell through its row and column. For example, let us consider ir_array[0][4] and here ir_array[0] tells first array of double with length 5 and second dimension [4] tells to locate the fifth element. Now consider the below code (Listing 4):

Listing 4

//Snippet 04: Now let us randomly take some value
// and print it.
System.out.println("ir_array[0][4] = " + ir_array[0][4]);
System.out.println("ir_array[1][2] = " + ir_array[1][2]);
System.out.println("ir_array[2][1] = " + ir_array[2][1]);

In the above code example, we picked three elements from the Jagged Array and displaying that in the console output window. The elements picked are shown in the below picture:

Picking an element from Jagged Array
Picking an element from Jagged Array | Source

6. Dynamically iterating all the elements of Ragged Array

The length property of the Array is useful to iterate the Jagged Array dynamically. Here in the below code ir_array denotes the “Array of Double Array” and its length is taken and iterated first. When we supply an index to ir-array, it represents the double Array as in that index we store the reference of the double array. When we read length property (For Example, ir_array[0].length,) it gives the length of the double array which is iterated as a nested loop.

In the below code snippet we iterated through all the array elements and printed the result to the console output window:

Listing 5.

//Snippet 05: Iterate through the Jagged Array
System.out.println("");
System.out.println("Iterating Through the Jagged Array");
for (int arrayofArrayIndex = 0;
     arrayofArrayIndex < ir_array.length;
     arrayofArrayIndex++) {

    for (int ArrayOfDoubleIndex = 0;
         ArrayOfDoubleIndex < ir_array[arrayofArrayIndex].length;
         ArrayOfDoubleIndex++) {
        System.out.print(
                ir_array[arrayofArrayIndex][ArrayOfDoubleIndex] + " ");
    }
    System.out.println("");
}

The complete example and its output is given below:


package com.JavaHub;

public class Main {

    public static void main(String[] args) {
        //Snippet 01: Declare an 2D Irregular Array
        double[][] ir_array = new double [3][];

        //Snippet 02: Now declare three arrays
        ir_array[0] = new double[5];
        ir_array[1] = new double[3];
        ir_array[2] = new double[2];

        //Snippet 03: Initialize the arrays
        for (int i = 0; i < 5; i++) {
            ir_array[0][i] = (i + 1) * 10;
        }

        for (int i = 0; i < 3; i++) {
            ir_array[1][i] = (i + 1) * 5;
        }

        for (int i = 0; i < 2; i++) {
            ir_array[2][i] = (i + 1) * 2;
        }

        //Snippet 04: Now let us randomly take some value
        // and print it.
        System.out.println("ir_array[0][4] = " + ir_array[0][4]);
        System.out.println("ir_array[1][2] = " + ir_array[1][2]);
        System.out.println("ir_array[2][1] = " + ir_array[2][1]);

        //Snippet 05: Iterate through the Jagged Array
        System.out.println("");
        System.out.println("Iterating Through the Jagged Array");
        for (int arrayofArrayIndex = 0;
             arrayofArrayIndex < ir_array.length;
             arrayofArrayIndex++) {

            for (int ArrayOfDoubleIndex = 0;
                 ArrayOfDoubleIndex < ir_array[arrayofArrayIndex].length;
                 ArrayOfDoubleIndex++) {
                System.out.print(
                        ir_array[arrayofArrayIndex][ArrayOfDoubleIndex]
                                + " ");
            }
            System.out.println("");
        }
    }
}
Ragged Array Example Output
Ragged Array Example Output | Source

© 2018 sirama

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, turbofuture.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://turbofuture.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)