Java support jagged arrays. A Jagged array is an array whose elements are arrays with different dimensions.
There are two ways to define a Jagged arrays.
a. Specify the jagged array size using array declaration
b. Define the array elements, let Java deduce the size
Specify the jagged array size using array declaration
Example
int arr[][] = new int[3][];
arr[0] = new int[2];
arr[1] = new int[6];
arr[2] = new int[4];
Above snippet define a two-dimensional array, where
a. arr[0] of size 2
b. arr[1] of size 6
c. arr[2] of size 4.
In the above example, 1st row is the longest among all the rows in the given 2-dimensional array.
Below snippet print the length of longest row.
int longestRow = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i].length > longestRow) {
longestRow = arr[i].length;
}
}
Find the below working application.
LongestRowLength.java
package com.sample.app;
public class LongestRowLength {
public static void main(String[] args) {
int[][] arr = {
{1, 2},
{5, 6, 7, 8, 13, 14},
{9, 10, 11, 12}
};
int longestRow = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i].length > longestRow) {
longestRow = arr[i].length;
}
}
System.out.println("Length of longest row is : " + longestRow);
}
}
Output
Length of longest row is 6
You may like
Java: Check whether a class exists in the classpath or not
How to get the name of calling class that invoke given method?
Implement map using array as storage
No comments:
Post a Comment