javacodex.com
Java Examples
Java Examples
memu home questions

Parallel Arrays

A parallel array is a data structure for representing arrays of records. Values located at the same index in each array are implicitly the fields of the same record.

Source: (ParallelArray.java)

public class ParallelArray {
 
   public static void main(String[] args) {
 
      int[] id = {1002, 423, 786};
      String[] name = {"John Doe", "Mary Jane", "Peter Pan"};
      String[] dept = {"Deli", "Pharmacy", "Produce"};
      double[] pay = {12.50, 13.75, 9.78};
 
      /* ----------------------------------------------
         Print the information in the parallel arrays
         ---------------------------------------------- */
      System.out.println("ID    Name        Department  Pay");
      System.out.println("----  ----------  ----------  -----");
      for ( int i = 0; i < id.length; i++ ) {
         System.out.printf( "%04d  ", id[i] );       
         System.out.printf( "%-10s  ", name[i] );  
         System.out.printf( "%-10s  ", dept[i] );  
         System.out.printf( "%5.2f" ,   pay[i] );
         System.out.println();
      }
   }
}
 

Output:

$ java ParallelArray 
ID    Name        Department  Pay
----  ----------  ----------  -----
1002  John Doe    Deli        12.50
0423  Mary Jane   Pharmacy    13.75
0786  Peter Pan   Produce      9.78

Contact: javacodex@yahoo.com