Previous Lecture Lecture 10 Next Lecture

Lecture 10, Mon 05/06

Generics, Multi-dimensional Arrays

Generics

Generic Methods

Example

// defining a method to be generic
public static <T> T getLastItem(T[] array) {
    if (array.length > 0) {
        return array[array.length - 1];
    }
    return null;
}
// in main
Integer[] intArray = {1,2,3}; // note: int[] error, requires Integer object
Double[] doubleArray = {1.1, 2.2, 3.3};
String[] stringArray = {"I", "<3", "CS56"};

System.out.println(getLastItem(intArray));
System.out.println(getLastItem(doubleArray));
System.out.println(getLastItem(stringArray));

Generic Classes

Example Pair class with one generic type

public class Pair<T> {
    private T first;
    private T second;

    public Pair(T first, T second) {
        this.first = first;
        this.second = second;
    }

    public T getFirst() {
        return first;
    }

    public T getSecond() {
        return second;
    }

    public void print() {
        System.out.println(first + ", " + second);
    }
}
// in main
Pair<Integer> pair = new Pair<Integer>(1,2);
System.out.println(pair.getFirst() + pair.getSecond());
pair.print();

Example Pair class with two generic types

public class Pair<T,U> {
    private T first;
    private U second;

    public Pair(T first, U second) {
        this.first = first;
        this.second = second;
    }

    public T getFirst() {
        return first;
    }

    public U getSecond() {
        return second;
    }

    public void print() {
        System.out.println(first + ", " + second);
    }
}
// in main
Pair<Integer, String> pair = new Pair<Integer, String>(1,"2");
System.out.println(pair.getFirst() + pair.getSecond());
pair.print();

2D Arrays

Example 4x5 Grid of int values

// in main
int[][] int2d = new int[4][5];

// traverse the entire 2D array structure and print it out in a matrix
for (int i = 0; i < int2d.length; i++) {
    for (int j = 0; j < int2d[i].length; j++) {
        System.out.print(int2d[i][j] + " ");
    }
    System.out.println();
}
int2d[1][3] = 8;

0 0 0 0 0
0 0 0 8 0
0 0 0 0 0
0 0 0 0 0
for (int i = 0; i < int2d.length; i++) {
    System.out.print("|");
    for (int j = 0; j < int2d[i].length; j++) {
        System.out.print(";");
        System.out.print(int2d[i][j] + " ");
    }
}

Multi-dimensional Arrays

int [][][] int3d = new int[2][3][2];
int3d[1][1][1] = 1;

for (int i = 0; i < int3d.length; i++) {
    System.out.print("|");
    for (int j = 0; j < int3d[0].length;j++) {
        System.out.print(";");
        for (int k = 0; k < int3d[0][0].length;k++) {
            System.out.print(int3d[i][j][k]);
        }
    }
}