Results 1 to 2 of 2
  1. #1
    chusui is offline Member
    Join Date
    Jun 2011
    Posts
    1
    Rep Power
    0

    Default length method for two-dimensional arrays

    I retrieved the length of both dimensions of the array k:

    int[][] k = new int[2][4];
    System.out.println(k.length); // displays "2"
    System.out.println(k[0].length); // displays "4"

    Is there a better way to retrieve the 2nd dimension? It seems not elegant to use k[0].length since it is arbitrary to pick "0" but not "1", "2", nor "3".

    Many thanks for your attention and help!

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,789
    Rep Power
    7

    Default

    Yes you must use arr[n].length. This works regardless of the type of array. For example you can have "jagged" 2D arrays.
    Java Code:
    int[][] arr = {{1,2}, {1,2,3,4,5}, {1,2,3,4}, {1,2,3,4,5,6}, {1,2,3}};
    for(int index = 0; index < arr.length; index++) {
        System.out.println(arr[index].length);
    }
    Remeber that a 2D array is simply a 1D array of 1D arrays.

Similar Threads

  1. Sorting Two Dimensional arrays
    By anfielder in forum New To Java
    Replies: 5
    Last Post: 12-14-2010, 07:12 AM
  2. two dimensional arrays
    By cliffh in forum New To Java
    Replies: 2
    Last Post: 11-05-2010, 11:43 PM
  3. Printing Two Dimensional Arrays with for loops
    By mcnam4119 in forum JCreator
    Replies: 3
    Last Post: 10-06-2010, 05:27 AM
  4. dynamic two dimensional arrays?
    By dinosoep in forum New To Java
    Replies: 4
    Last Post: 12-05-2009, 06:12 PM
  5. Multi-dimensional arrays
    By Implode in forum New To Java
    Replies: 1
    Last Post: 09-15-2009, 08:50 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •