Multi-dimensional arrays in Java

Discussion in 'Java' started by pradeep, Aug 11, 2006.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Multi-dimensional arrays

    Java, as with most languages, supports multi-dimensional arrays - 1-dimensional, 2-dimensional, 3-dimensional, ... This discusses 2-dimensional arrays, but the same principles apply to higher dimensions.

    2-dimensional arrays


    2-dimensional arrays are usually represented in a row-column approach on paper, and the terms "rows" and "columns" are used in computing.
    Arrays of arrays

    There are two ways to implement 2-dimensional arrays. Many languages reserve a block of memory large enough to hold all elements of the full, rectangular, array (number of rows times number of columns times the element size). Java doesn't do this. Instead Java builds multi-dimensional arrays from many one-dimensional arrays, the so-called "arrays of arrays" approach. [C++ supports both styles.]

    There are a couple of interesting consequences of this: Rows may be different sizes. Also, each row is an object (an array) that can be used independently.

    Declaration

    Declare a 2-dimensional array as follows:

    Code:
    int[][] a2; // Declares, but doesn't allocate, 2-dim array.
    Allocation

    As with all arrays, the new keyword must be used to allocate memory for an array. For example,

    Code:
    int[][] a2 = new int[10][5];
    This allocates an int array with 10 rows and 5 columns. As with all objects, the values are initialized to zero (unlike local variables which are uninitialized).

    This actually allocates 6 objects: a one-dimensional array of 5 elements for each of the rows, and a one-dimensional array of ten elements, with each element pointing to the appropriate row array.

    Processing 2-dimensional arrays

    Often 2-dimensional arrays are processed with nested for loops. Notice in the following example how the rows are handled as separate objects. For example,

    Code:
    int[][] a2 = new int[10][5];
     // print array in rectangular form
     for (int r=0; r<a2.length; r++) {
         for (int c=0; c<a2[r].length; c++) {
             System.out.print(" " + a2[r][c]);
         }
         System.out.println("");
     }
     
    Uneven rows

    One consequence of arrays of arrays is that each row can be a different size ("ragged" arrays). For example, we could create a lower triangular array, allocating each row "by hand" as follows.

    Code:
    int[][] tri;
     tri = new int[10][];  // allocate array of rows
     for (int r=0; r<tri.length; r++) {
         tri[r] = new int[r+1];
     }
     
     // print the triangular array (same as above really)
     for (int r=0; r<tri.length; r++) {
         for (int c=0; c<tri[r].length; c++) {
             System.out.print(" " + tri[r][c]);
         }
         System.out.println("");
     }
     
  2. abcdou

    abcdou New Member

    Joined:
    Aug 11, 2006
    Messages:
    8
    Likes Received:
    0
    Trophy Points:
    0
    hi pradeep!

    how about if the user will input student information?
    Label(row 0) Lastname firstname address
    dou abc malaysia

    There are method()
    1.Assign name
    2.Display name
    3.Sort name in ascending
    4.Search name

    how to do this pradeep
    pls........
     
  3. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    We will use a multi-dimensional array.

    Code:
     String[][] Data;
     
     //Assign the values, do it either dynamically or statically
     //For first fow
     Data[0][0] = "S"; //lastname
     Data[0][1] = "Pradeep"; //firstname
     Data[0][2] = "Kolkata"; //location
     
     //Second row
     Data[1][0] = "Bhimani"; //lastname
      Data[1][1] = "Shabbir"; //firstname
      Data[1][2] = "Kolkata"; //location
     
     //Add as many rows you want
     
     //printing
     System.out.print("Lastname\tFirstname\tLocation\n");
     for(i=0;i<2;i++)
     {
       for(j=0;j<3;j++)
       {
         System.out.print(Data[i][j]+"\t");
       }
       //move to new line
       System.out.print("\n");
     }

    This should do the work for you.
     
    Lahiru Palliyaguru likes this.
  4. abcdou

    abcdou New Member

    Joined:
    Aug 11, 2006
    Messages:
    8
    Likes Received:
    0
    Trophy Points:
    0
    thank you pradeep!!!

    how about sorting and searching?

    do you have any tutorial in two dimensional array?


    thanks.....
     
  5. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    You can use simple sorting algorithms like Bubble Sort,Selection Sort to sort the array data. Multi-dimensional array concepts can be applied to two-dimensional arrays. You are free to ask any specific questions you have about two-dimensional arrays.
     
  6. abcdou

    abcdou New Member

    Joined:
    Aug 11, 2006
    Messages:
    8
    Likes Received:
    0
    Trophy Points:
    0
    how about in searching?

    thanks pradeep
     
  7. champion

    champion New Member

    Joined:
    May 29, 2007
    Messages:
    9
    Likes Received:
    1
    Trophy Points:
    0
    Occupation:
    Analyst Programer
    Location:
    Harare, Zimbabwe
    How do we test if the array is null not testing for a null element?
     
    Lahiru Palliyaguru likes this.
  8. champion

    champion New Member

    Joined:
    May 29, 2007
    Messages:
    9
    Likes Received:
    1
    Trophy Points:
    0
    Occupation:
    Analyst Programer
    Location:
    Harare, Zimbabwe
    How do we test if the array is null not testing for a null element?
     
  9. shilpa dessai

    shilpa dessai New Member

    Joined:
    Mar 20, 2008
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Pradeep please reply soon we have to complete our project and we are stuck only due to this sorting code.......
     
  10. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Please post the 1D sorting you have already written!
     
  11. itzkloive

    itzkloive New Member

    Joined:
    Mar 23, 2008
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    electronic
    Location:
    NJ
    Can some one help a novice

    I am kinda teaching myself java and got stuck trying to create a a program to translate 10 words bi-directional from english to spaniah, using two different String Arrays one consist of english words and one consist of spanish words. Can someone help this novice out?


    import java.io.*;//tell Java we are using java.io libary.
    import java.util.*;//Java utility package also for Scanner class

    public class transWords //Naming the program.
    {

    public static void main(String[ ]args)throws Exception
    {
    //This set-up allow for user to input using keyboard.
    Scanner input= new Scanner(System.in);


    //Declaring Array String.
    String[]englishTrans={"color","white","blue","green","black","purple",};
    //Declaring Array String.
    String[]spanishTrans={"en color","blanco","azul","verde","negro","purpúreo",};
     
  12. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    What's the exact nature of help you are looking for? the code snippet is probably incomplete!
     
  13. shilpa dessai

    shilpa dessai New Member

    Joined:
    Mar 20, 2008
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    hi Pradeep,
    For sorting a 1D array we used the simply Bubble sort aLgorithm which worked perfectly fine...but we cant write the code 4 the 2D array as we had written earlier....
    thx...
    Shilpa
     
  14. Mazharul

    Mazharul New Member

    Joined:
    Aug 11, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    sir,
    i want to show a 2D array corresponding to a .jpg/.gif/.png image file in a separate window. suppose i have...
    class Image {
    protected int width,height;
    // 'samples' stores the image pixel values.
    protected int[][] samples;
    // Constructor: Reads the image from the
    // specified file name.
    public Image(String filename)
    throws Exception { read(filename); }
    // Returns the pixel width of the image.
    public int getWidth() { return width; }
    // Returns the pixel height of the image.
    public int getHeight() { return height; }
    // Reads the image from the specified file
    // name into the 'samples' array. Throws an
    // exception if the image is stored in an
    // unsupported file format (currently only
    // .GIF, .JPG, and .PNG are supported by Sun).
    public void read(String filename)
    throws Exception {
    // Extract the file name suffix...
    .......
    ...........
    .............
    from the startup java file like..
    import java.awt.*;
    import javax.imageio.*;
    class TestImage {
    public static void main(String args[])
    throws Exception {
    // Create a frame to display the image.
    Frame frame = new Frame("Test Image");
    frame.setSize(1024,768);
    frame.setVisible(true);
    Graphics gc = frame.getGraphics();
    try {
    // Read the image from the file.
    Image img = new Image("Horse.jpg");
    .........

    I want to access the int [][] samples array then want to disply this array values in a separate windo or applet..How to approach......
     
  15. majidpucit123

    majidpucit123 New Member

    Joined:
    Sep 7, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    i'm trying to create a method that adds an element in an existing string array. Kind of like the arraylist "add()" method.
    so far, i have this

    String[] addToArray(String[] strArray1, String s)
    {
    return strArray1+s;

    }



    but this doesnt work...
    why?
    :worried:
     
  16. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    There already exists such a method, it's called push!
     
  17. new2Java

    new2Java New Member

    Joined:
    Dec 9, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi!

    I need to compare 2 words in a given name and see if any part of the name in index [0] (first name and/or surname) matches the rest of the names. For instance,

    robert smith | robert mathews | john robert | john roberts

    Basically, only the first and lastname in the first index ("robert smith") needs to be compared with rest of the first and the last names. '

    How do I go about this?

    I'm successful in comparing just 1 word. eg: robert|RoBERT|smith
    boolean result1= choiceKeys[0].equalsIgnoreCase (choiceKeys[i+1]);

    What should I do when I have 2 words?

    Thanks in advance,
    -new2Java
     
  18. thusha

    thusha New Member

    Joined:
    Aug 13, 2009
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hai
    I am inteested in adding elements to 2D array.
    So i do like this
    i have always one input as prod id ; where i get from parameter

    then the for loop
    Code:
    [COLOR=navy][B]int[/B][/COLOR] n = productsid;
                      
                                   [COLOR=navy][B]for[/B][/COLOR]( row=0;row<10;row++) [COLOR=navy]{[/COLOR]              	
                	year2007[n][row] = ([COLOR=navy][B]float[/B][/COLOR]) tot;
                   [COLOR=navy]}[/COLOR]
    
    
    
    
    but when i display my array
    i dont get the prod id?? what ican do ??
     
  19. Theone

    Theone New Member

    Joined:
    Dec 17, 2009
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Hi Pradeep,
    Can you use a 2d array to make a chess board and store the pieces within it?.
     
  20. technica

    technica New Member

    Joined:
    Dec 15, 2007
    Messages:
    107
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    http://www.technicaltalk.net
    Thanks for posting. A article on handling arrays for sorting and searching would be great.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice