Ragged array

Posted By on September 16, 2014


Download PDF
2D Array
Java Methods

Ragged arrays

The two dimensional array illustrated in the previous section was a regular array; that is, all of the component arrays which form its second dimension had exactly the same length. This is not always appropriate; for example a salary structure may have two grades, A and B, with a different number of points on each grade. An example is given in Figure 13.2.a).

FigureĀ  a and b. Lecturers’ salaries and data structure diagram.
The data structure diagram for this table cannot indicate the size of a grade as the Lecturer A grade has four points but the Lecturer B grade has only two points. A class to implement this data structure is as follows.

0001  // Filename RaggedArray.java.
0002  // Illustrates the construction and use of a
0003  // two dimensional ragged array.
0004  //
0005  // Written for JFL Book Chapter 13.
0006  // Fintan Culwin, V 0.1, Jan 1997.
0007
0008  class RaggedArray {
0009
0010  private int salaries[][];
0011
0012     public RaggedArray() {
0013
0014        salaries = new int[ 2] [];
0015
0016        salaries[ 0] = new int[ 4];
0017        salaries[ 0] [ 0] = 12345;  salaries[ 0] [ 1] = 23456;
0018        salaries[ 0] [ 2] = 34567;  salaries[ 0] [ 3] = 45678;
0019
0020        salaries[ 1] = new int[ 2];
0021        salaries[ 1] [ 0] = 56789;  salaries[ 1] [ 1] = 67890;
0022     } // End RaggedArray default constructor.
0023
0024
0025     public String toString() {
0026
0027     StringBuffer    theBuffer = new StringBuffer();
0028     int thisIndex, anotherIndex;
0029
0030        for ( thisIndex = 0;
0031              thisIndex < salaries.length;
0032              thisIndex++) {
0033           for( anotherIndex = 0;
0034                anotherIndex < salaries[ thisIndex].length;
0035                anotherIndex++) {
0036              theBuffer.append( Integer.toString(
0037                                   salaries[ thisIndex] [ anotherIndex]) +
0038                                   "    ");
0039           } // End for anotherIndex.
0040           theBuffer.append("n");
0041        } // End for thisIndex.
0042        return theBuffer.toString();
0043     } // End toString.
0044
0045  } // End class RaggedArray.

2D Array
Java Methods

Download PDF

Posted by Akash Kurup

Founder and C.E.O, World4Engineers Educationist and Entrepreneur by passion. Orator and blogger by hobby

Website: http://world4engineers.com