Overview

  • Arrays

    Multiple values of common type.

    Loop style handling.

    Lecture notes

Motivating Arrays

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);
...

Lecture notes

  • Arrays

Create comment

Per member repeating tasks

  • 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>

Lecture notes

  • Arrays

Create comment

Example: int array of primes

final int[] primes  = new int[5]; 

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

Lecture notes

  • Arrays

Create comment

Loop prime values

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

Lecture notes

  • Arrays

Create comment

Mind the limit!

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)

Lecture notes

  • Arrays

Create comment

Safer: Using length

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

Lecture notes

  • Arrays

Create comment

Even better: for-each style loop

for (final int p: primes) {
  System.out.println("value == " + p);
}
Result:
value == 2
value == 3
value == 5
value == 7
value == 11

Lecture notes

  • Arrays

Create comment

Mind the limit, part two

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)

Lecture notes

  • Arrays

Create comment

One step initialization

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;

Lecture notes

  • Arrays

Create comment

Followup exercises

Array

  • 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.

Lecture notes

  • Arrays

Create comment

Two syntax variants

  1. type[] arrayName;
  2. type arrayName[];

Lecture notes

  • Arrays

Create comment

Array instances are special!

...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;

Lecture notes

  • Arrays

Create comment

Array creation details

layered SVG image

Lecture notes

  • Arrays

Create comment

Array creation details

layered SVG image

Lecture notes

  • Arrays

Create comment

Array creation details

layered SVG image

Lecture notes

  • Arrays

Create comment

Array creation details

layered SVG image

Lecture notes

  • Arrays

Create comment

Array creation details

layered SVG image

Lecture notes

  • Arrays

Create comment

Array parameter passing

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

Lecture notes

  • Arrays

Create comment

Parameter passing details

layered SVG image

Lecture notes

  • Arrays

Create comment

Parameter passing details

layered SVG image

Lecture notes

  • Arrays

Create comment

Parameter passing details

layered SVG image

Lecture notes

  • Arrays

Create comment

Parameter passing details

layered SVG image

Lecture notes

  • Arrays

Create comment

Parameter passing details

layered SVG image

Lecture notes

  • Arrays

Create comment

Parameter passing details

layered SVG image

Lecture notes

  • Arrays

Create comment

Parameter passing details

layered SVG image

Lecture notes

  • Arrays

Create comment

Parameter passing details

layered SVG image

Lecture notes

  • Arrays

Create comment

Parameter passing details

layered SVG image

Lecture notes

  • Arrays

Create comment

Parameter passing details

layered SVG image

Lecture notes

  • Arrays

Create comment

Parameter passing details

layered SVG image

Lecture notes

  • Arrays

Create comment

Parameter passing details

layered SVG image

Lecture notes

  • Arrays

Create comment

Value and reference types

// 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"};

Lecture notes

  • Arrays

Create comment

Overview

  • Arrays
    • ➟ java.util.Arrays helpers

      Sorting and searching arrays.

      Fill in values.

      Compare array contents.

      Lecture notes

Arrays.toString(...) and Arrays.sort(...)

final String[] names = {"Eve", "Aaron", "Paul", "Mandy"};

System.out.println("     toString: " + Arrays.toString(names));

Arrays.sort(names);

System.out.println("sort|toString: " + Arrays.toString(names));

Result:

     toString: [Eve, Aaron, Paul, Mandy]
sort|toString: [Aaron, Eve, Mandy, Paul]

Lecture notes

  • Arrays
    • ➟ java.util.Arrays helpers

Create comment

Arrays.binarySearch(...)

final String[] names = {"Aaron", "Eve", "Mandy",  "Paul"};

// Precondition: Array must be ordered!
...println("sort|find(Mand): " + Arrays.binarySearch(names, "Mand"));
...println("sort|find(Mandy): " + Arrays.binarySearch(names, "Mandy"));
...println("sort|find(Mandyer): " + Arrays.binarySearch(names, "Mandyer"));

Result:

sort|find(Mand): -3
sort|find(Mandy): 2
sort|find(Mandyer): -4

Lecture notes

  • Arrays
    • ➟ java.util.Arrays helpers

Create comment

Followup exercise

No. 136: Understanding search results

Arrays.fill(...)

final String[] names = 
  {"Eve", "Aaron", "Paul", "Mandy"};

System.out.println("toString: " +
   Arrays.toString(names));

Arrays.fill(names, "N.N");

System.out.println("toString: " + 
    Arrays.toString(names));
toString: [Eve, Aaron, Paul, Mandy]
toString: [N.N, N.N, N.N, N.N]

Lecture notes

  • Arrays
    • ➟ java.util.Arrays helpers

Create comment

Arrays.copyOfRange(...)

final String[] names = {"Eve", "Aaron", "Paul", "Mandy"};

final String[] lastTwoNames = Arrays.copyOfRange(names, 2, 6);

System.out.println("toString: " + Arrays.toString(lastTwoNames));

Result:

toString: [Paul, Mandy, null, null]

Lecture notes

  • Arrays
    • ➟ java.util.Arrays helpers

Create comment

Arrays.equals(...)

final String[]
  l1 = {"Eve", "Aaron", "Paul", "Mandy"},
  l2 = {"Eve", "Aaron", "Paul", "Mandy"},
  l3 = {"Eve", "Aaron", "Paul", "Mobile"};

System.out.println("l1.equals(l2):" + Arrays.equals(l1, l2));
System.out.println("l1.equals(l3):" + Arrays.equals(l1, l3));

Result:

l1.equals(l2):true
l1.equals(l3):false

Lecture notes

  • Arrays
    • ➟ java.util.Arrays helpers

Create comment

Overview

  • Arrays
    • ➟ Extending arrays

      Dealing with fixed size.

      Lecture notes

Lack of extendability

final String[] member = {"Eve", "John", "Peter", "Jill"};

final String newCourseMember = "Ernest";

member.length = 5; // Error: Size unchangeable

member[4] =  newCourseMember;

Lecture notes

  • Arrays
    • ➟ Extending arrays

Create comment

Extending an array

public static void main(String[] args) {
  String[] member = {"Eve", "John", "Peter", "Jill"};
  final String newMember = "Ernest";
  member = append(member, newMember);
}
static String[] append (final String[] values, final String newValue) {
  final String[] copy =  new String[values.length + 1];
  for (int i = 0; i < values.length; i++) { 
    copy[i] = values[i]; 
  }
  copy[copy.length - 1] = newValue; 
  return copy;
}

Lecture notes

  • Arrays
    • ➟ Extending arrays

Create comment

Extension result

final String[] member = {"Eve", "John", "Peter", "Jill"};
System.out.println("Original array: " + Arrays.toString(member));
final String newMember = "Ernest";
member = append(member, newMember);
System.out.println("Extended array: " + Arrays.toString(member));
Original array: [Eve, John, Peter, Jill]
Extended array: [Eve, John, Peter, Jill, Ernest]

Lecture notes

  • Arrays
    • ➟ Extending arrays

Create comment

Using Arrays.copyOf()

public static void main(String[] args) {
    final int [] start = {1,7,-4},
    added = append(start, 77);
    System.out.println("added: " + Arrays.toString(added));
  }
static public int[] append(final int[] values, final int newValue) {
  final int[] result = Arrays.copyOf(values, values.length + 1);
  result[values.length] = newValue;
  return result;}

Result:

added: [1, 7, -4, 77]

Lecture notes

  • Arrays
    • ➟ Extending arrays

Create comment

Followup exercises

Overview

  • Arrays
    • ➟ Understanding static public int main(String[] args)

      main(...) and its array argument.

      Implementing parameter passing.

      Lecture notes

public static void main(String[] args)

package myapp;
public class Cmd {
  public static void main(String[] args) {
    for (int i = 0; i < args.length; i++) {
      System.out.println("Parameter " + (i + 1) + ": " + args[i]);
    }
  }
}
java myapp.Cmd 21 334 -13
Parameter 1: 21
Parameter 2: 334
Parameter 3: -13

Lecture notes

  • Arrays
    • ➟ Understanding static public int main(String[] args)

Create comment

Intellij IDEA run configuration

Intellij IDEA run configuration

Entry class myapp.Cmd containing ... main(String[] args).

Parameters 21, 334 and -13 being passed to String[] args.

Lecture notes

  • Arrays
    • ➟ Understanding static public int main(String[] args)

Create comment

Intellij IDEA run configuration

Intellij IDEA run configuration

Lecture notes

  • Arrays
    • ➟ Understanding static public int main(String[] args)

Create comment

Creating executable jar

<artifactId>maven-shade-plugin</artifactId>
...
<transformer ...>
  <manifestEntries>
    <Main-Class>myapp.Cmd</Main-Class>
  </manifestEntries>...
unzip ww-1.0-SNAPSHOT.jar
cat  tmp/META-INF/MANIFEST.MF
...
Created-By: Apache Maven 3.5.0
Build-Jdk: 1.8.0_151
Main-Class: myapp.Cmd
mvn package ...
java -jar target/ww-1.0-SNAPSHOT.jar 21 334 -13
Parameter 1: 21
Parameter 2: 334
Parameter 3: -13

Lecture notes

  • Arrays
    • ➟ Understanding static public int main(String[] args)

Create comment

Followup exercises

Overview

  • Arrays
    • ➟ Multi-dimensional arrays

      Multiple dimensions by nesting of arrays.

      Lecture notes

Two-dimensional arrays

int[][] matrix = new int[2][3];

for (int row = 0; row < 2; row++) {
  for (int col = 0; col < 3; col++) {
    matrix[row][col] = col + row;
  }
}
for (int row = 0; row < 2; row++) {
  System.out.println(Arrays.toString(matrix[row]));
}

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Behind the scenes

final int[][] matrix = new int[2][]; // Array containing two int arrays
matrix[0] = new int[3];              // first int array
matrix[1] = new int[3];              // second int array

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Memory allocation

layered SVG image

Lecture notes

  • Arrays
    • ➟ Multi-dimensional arrays

Create comment

Followup exercises