Arrays

Related slides on offer

Figure 379. Motivating Arrays Slide presentation Create comment in forum
final String
      karen = "Karen Smith",
      john = "John Duncan",
      paul = "Paul Jacobs",
      suzanne = "Suzanne Enders",
      peter = "Peter Phillips";  // 10 more to come ...

    System.out.println(karen);
    System.out.println(john);
...

Figure 380. Per member repeating tasks Slide presentation Create comment in forum
  • Generate Comma separated list:

    Karen Smith, John Duncan, Paul Jacobs, Suzanne Enders, Peter Phillips
  • Generate HTML list emphasizing family names:

    <ul>
      <li>Karen <emph>Smith</emph></li>
      <li>John <emph>Duncan</emph></li>
      <li>Paul <emph>Jacobs</emph></li>
      <li>Suzanne <emph>Enders</emph></li>
      <li>Peter <emph>Phillips</emph></li>
    </ul>

Figure 381. Example: int array of primes Slide presentation Create comment in forum
final int[] primes  = new int[5]; 

primes[0] = 2; 
primes[1] = 3;
primes[2] = 5;
primes[3] = 7;
primes[4] = 11;

int array reference variable primes.

int array allocation capable to store five values and assigning its reference to variable primes.

Assigning values referencing array positions by index values from {0,1,2,3,4}.

Figure 382. Loop prime values Slide presentation Create comment in forum
for (int i = 0; i < 5; i++) {
  System.out.println("At index " + i + ": value == " + primes[i]);
}

Result:

At index 0: value == 2
At index 1: value == 3
At index 2: value == 5
At index 3: value == 7
At index 4: value == 11

Figure 383. Mind the limit! Slide presentation Create comment in forum
for (int i = 0; i < 6; i++) {
  System.out.println("At index " + i + ": value == " + primes[i]);
}
Result:
At index 0: value == 2
At index 1: value == 3
At index 2: value == 5
At index 3: value == 7
At index 4: value == 11
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
  at qq.arrayex.Motivate.main(Motivate.java:27)

Figure 384. Safer: Using length Slide presentation Create comment in forum
System.out.println("primes.length == " + primes.length);
for (int i = 0; i < primes.length; i++) {
  System.out.println("At index " + i + ": value == " + primes[i]);
}
Result:
primes.length == 5
At index 0: value == 2
At index 1: value == 3
At index 2: value == 5
At index 3: value == 7
At index 4: value == 11

Figure 385. Even better: for-each style loop Slide presentation Create comment in forum
for (final int p: primes) {
  System.out.println("value == " + p);
}
Result:
value == 2
value == 3
value == 5
value == 7
value == 11

Figure 386. Mind the limit, part two Slide presentation Create comment in forum
final int[] primes = new int[5]; // Last index is 4 rather than 5!

primes[0] = 2;
primes[1] = 3;
primes[2] = 5;
primes[3] = 7;
primes[4] = 11;
primes[5] = 13; // Excessing array limit
Result:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
  at qq.arrayex.Motivate.main(Motivate.java:25)

Figure 387. One step initialization Slide presentation Create comment in forum

Combining array allocation and value assignment:

final int[]
  primes = {2, 3, 5, 7, 11};
final int[] primes = new int[5];
primes[0] = 2;
primes[1] = 3;
primes[2] = 5;
primes[3] = 7;
primes[4] = 11;

exercise No. 129

Converting string arrays to HTML. Create comment in forum

Q:

Consider an array of strings. As an example we provide a list of country names:

final String[] countries = {
        "England"
        ,"France"
        ,"Germany"
};

An application is supposed to generate the following output:

<ul>
  <li>England</li>
  <li>France</li>
  <li>Germany</li>
</ul>

Implement A class method strings2html(final String [] strings) as in:

public class Stringarray2Html {

  /**
   * Create an unordered ...
   *  ...
   */
  static public String strings2html(final String [] strings) {
    ...
    return ...;
  }
}

Do not forget to provide appropriate Javadoc method and class documentation. You may want to reconsider Figure 44, “Maven javadoc:javadoc.

Generating Javadoc HTML documentation from your project should yield a result like:

Provide appropriate unit tests covering at least:

  • An empty input array.

  • An input array containing at least two strings.

A:

exercise No. 130

Route navigation Create comment in forum

Q:

We want to estimate the amount of time being required driving a particular route. Consider the following example:

The route above may be dissected into several legs:

  1. From starting point to motorway

  2. Motorway till through road

  3. Through road till junction

  4. Junction till destination

Each leg may have a different speed limit. We thus define:

public class Segment {

   /**
    * Indication a segment does not have any speed limit.
    */
   static public final int NO_SPEED_LIMIT = 0;

   /**
    * The distance of the current leg in km.
    */
   public final double distance;

   /**
    * The current leg's speed limit in km / h.
    */
   public final int speedLimit;

   /**
    * Creating an (immutable) leg
    * @param distance {@link #distance}
    * @param speedLimit {@link #speedLimit}
    */
   public Segment(final double distance, final int speedLimit) {
      this.distance = distance;
      this.speedLimit = speedLimit;
   }
}

A given route will be defined by an array of segments:

final Segment[] route = new Segment[] {
   new Segment(2.4, 50)
  ,new Segment(5, 100)
  ,new Segment(3.1, 50)
  ,new Segment(0.8, 30)
};

Implement a method duration(...) which allows for calculation the minimum expected time required with respect to speed limits along a given route.

/**
 * Minimal time required when consequently traveling with the minimum of
 * official speed limits and the driver's personal maximum speed. If a
 * leg does not have any speed limit the value of personalSpeedLimit will
 * be used for calculation instead.
 *
 * @param route The array of segments composing a route.
 *
 * @param personalSpeedLimit The drivers personal speed limit whether or
 *        not official limits apply. Must be greater than 0.
 *
 * @return The minimal duration in (rounded) minutes with respect to all
 *         speed limits. Must be a positive (non-zero) value.
*/
static public long duration(Segment[] route, int personalSpeedLimit) {
  return 0; // TODO
}

Write Junit tests to cover different situations.

Tip

You may want to start implementing a main() method example first to gain some experience:

public class Driver {
   /**
    * @param args unused
    */
   public static void main(String[] args) {

      final Segment[] route = new Segment[] {
            new Segment(2.4, 50)
            ,new Segment(5, 100)
            ,new Segment(3.1, 50)
            ,new Segment(0.8, 30)
      };
      ...

      final long fullMinutes = ...;

      System.out.println("Minimal duration:" + fullMinutes);
}

A:

exercise No. 131

Examinations and mark frequencies Create comment in forum

Q:

Consider an examination resulting in the following list of marks:

Participant no. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Mark 2 1 3 3 5 4 1 2 2 4 3 2 3 3 1 5 3 4

You may represent this examination result by:

final int[] marks = {2,1,3,3,5,4,1,2,2,4,3,2,3,3,1,5,3,4};

Lecturers and participants may be interested in the distribution of marks i.e. their frequencies. Thus having marks in a range from 1 to 5 in the given example we'd like to create the following overview of marks:

Mark Frequency
1 3
2 4
3 6
4 3
5 2

Write a Java application which turning an array of participants' marks into a table of mark frequencies. For the given example the intended terminal output reads:

Mark|frequency
----+---------
   1|3
   2|4
   3|6
   4|3
   5|2

Your application shall work for other marking schemes (i.e. marks ranging from -2 to 10) as well. Define a suitable class like:

public class MarkFrequencies {

  public final int[] frequencyByMark;
  public final int lowestMark;

  public MarkFrequencies(final int[] markValues) {
    ...
  }
}

The constructor is yet not implemented. Upon completion you may use class MarkFrequencies producing the previously detailed terminal output:

public static void main(String[] args) {

  final MarkFrequencies markFrequencies =
    new MarkFrequencies(new int[]{2,1,3,3,5,4,1,2,2,4,3,2,3,3,1,5,3,4});

  // Create overview of marks:
  //
  System.out.println("Mark|frequency");
  System.out.println("----+---------");

  for (int i = 0; i < markFrequencies.frequencyByMark.length ; i++) {
    System.out.println("   " + (markFrequencies.lowestMark + i) + "|" +
      markFrequencies.frequencyByMark[i]);
  }
}

providing appropriate unit tests beforehand.

Tip

  1. Get the maximum and minimum mark of all participants.

  2. Create the int[] frequencyByMark array. Regard each mark value as an index value. So if the mark value range is e.g. {-2, -1, 0, 1, 2, 3} map these to index values {0, 1, 2, 3, 4, 5}. Then use each element from the list of marks as an index to this array and increment the respective index position accordingly.

After implementing your method extend your application to allow for being called from the command line like:

marking> mvn package
  ....
marking> java -jar target/marking-0.9.jar 2 1 3 3 5 4 1 2 2 4 3 2 3 3 1 5 3 4

Mark|frequency
----+---------
   1|3
   2|4
   3|6
   4|3
   5|2

This requires evaluating the args parameter from your main(String[] args) method.

Tip

  1. Converting a string like "5" into an int value of 5 may be achieved using:

    int value = Integer.valueOf()
  2. The maven-shade-plugin already being configured inside your project's pom.xml allows for creating executable jar archives. Suppose a main(...) method exists in a class de.hdm_stuttgart.mi.marking.Marks: Your project's pom.xml allows for defining this class to become the archive's executable method:

    ...
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-shade-plugin</artifactId>
      <version>3.1.0</version>
      <configuration>
        <transformers>
          <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
            <manifestEntries>
              <Main-Class>de.hdm_stuttgart.mi.marking.Marks</Main-Class>
            </manifestEntries>
          </transformer>
        </transformers>
      </configuration>
      <executions>
        <execution>
          <phase>package</phase>
          <goals>
            <goal>shade</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
    ...

    Executing the mvn package phase will then create an executable jar archive as outlined above.

A:

The method int[] de.hdm_stuttgart.mi.marking.Marks.getFrequencies(int[] values) is being defined in a slightly more general way possibly being useful in similar situations as well. This way it becomes subject to unit testing:

public class AppTest {

  @Test
  public void testSingle() {
      Assert.assertArrayEquals(
          new int[]{1},
          Marks.getFrequencies(new int[]{-3}));
  }

  @Test
  public void testMultiple() {
      Assert.assertArrayEquals(
          new int[]{2, 1, 0, 0, 0, 2, 0, 3},
          Marks.getFrequencies(new int[]{-3, 4 , 2, -2, 4, -3, 2, 4}));
  }
}
Figure 388. Array Slide presentation Create comment in forum
  • Series of objects having identical type.

  • Array consists of array elements.

  • Element access by index value.

  • Holding either primitive types or object references.

  • Contiguous storage in memory.

  • Arbitrary dimensions: One-dimensional, two-dimensional etc.


Figure 389. Two syntax variants Slide presentation Create comment in forum
  1. type[] arrayName;
  2. type arrayName[];

Figure 390. Array instances are special! Slide presentation Create comment in forum
...println("        String: " + "".getClass().getName());
...println("         int[]: " + new int[]{}.getClass().getName());
...println("      double[]: " + new double[]{}.getClass().getName());
...println("     boolean[]: " + new boolean[]{}.getClass().getName());
...println("      String[]: " + new String[]{}.getClass().getName());
...println("StringBuffer[]: " + new StringBuffer[]{}.getClass().getName());
        String: java.lang.String
         int[]: [I
      double[]: [D
     boolean[]: [Z
      String[]: [Ljava.lang.String;
StringBuffer[]: [Ljava.lang.StringBuffer;

Figure 391. Array creation details Slide presentation Create comment in forum

Figure 392. Array parameter passing Slide presentation Create comment in forum
public static void main(String[] args) {
  final int [] lectures = new int[3]; // Three lectures
  fill(lectures, 25); // Default lecture having 25 participants
  System.out.println("Second lecture has got " + lectures[1] +
          " participants");
}
/**
  * Initialize array with default value.
  *
  * @param values Array to be initialized.
  * @param common Common value for all array elements.
  */
static void fill(final int[] values, final int common) {
  for (int i = 0; i < values.length; i++) {
    values[i] = common;
  }
}
Second lecture has got 25 participants

Figure 393. Parameter passing details Slide presentation Create comment in forum

Figure 394. Value and reference types Slide presentation Create comment in forum
// Value type
final boolean values[] = new boolean[]{true, true, false, true};

// Reference type
final String shapes[] = new String[]{"Triangle", "Circle"};

Same result:

final boolean values[] = {true, true, false, true};

final String shapes[] = {"Triangle", "Circle"};