Skip to content

Instantly share code, notes, and snippets.

@rjlutz
Created October 19, 2017 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjlutz/2d99faffebf1b493e1db884764830260 to your computer and use it in GitHub Desktop.
Save rjlutz/2d99faffebf1b493e1db884764830260 to your computer and use it in GitHub Desktop.
Java Generics (Chapter 19) -- examples from Liang Intro to Java Comprehensive 10e
public class AnyWildCardDemo {
public static void main(String[] args ) {
GenericStack<Integer> intStack = new GenericStack<Integer>();
intStack.push(1); // 1 is autoboxed into new Integer(1)
intStack.push(2);
intStack.push(-2);
print(intStack);
}
/** Print objects and empties the stack */
public static void print(GenericStack<?> stack) {
while (!stack.isEmpty()) {
System.out.print(stack.pop() + " ");
}
}
}
public abstract class GenericMatrix<E extends Number> {
/** Abstract method for adding two elements of the matrices */
protected abstract E add(E o1, E o2);
/** Abstract method for multiplying two elements of the matrices */
protected abstract E multiply(E o1, E o2);
/** Abstract method for defining zero for the matrix element */
protected abstract E zero();
/** Add two matrices */
public E[][] addMatrix(E[][] matrix1, E[][] matrix2) {
// Check bounds of the two matrices
if ((matrix1.length != matrix2.length) ||
(matrix1[0].length != matrix2[0].length)) {
throw new RuntimeException(
"The matrices do not have the same size");
}
E[][] result =
(E[][])new Number[matrix1.length][matrix1[0].length];
// Perform addition
for (int i = 0; i < result.length; i++)
for (int j = 0; j < result[i].length; j++) {
result[i][j] = add(matrix1[i][j], matrix2[i][j]);
}
return result;
}
/** Multiply two matrices */
public E[][] multiplyMatrix(E[][] matrix1, E[][] matrix2) {
// Check bounds
if (matrix1[0].length != matrix2.length) {
throw new RuntimeException(
"The matrices do not have compatible size");
}
// Create result matrix
E[][] result =
(E[][])new Number[matrix1.length][matrix2[0].length];
// Perform multiplication of two matrices
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++) {
result[i][j] = zero();
for (int k = 0; k < matrix1[0].length; k++) {
result[i][j] = add(result[i][j],
multiply(matrix1[i][k], matrix2[k][j]));
}
}
}
return result;
}
/** Print matrices, the operator, and their operation result */
public static void printResult(
Number[][] m1, Number[][] m2, Number[][] m3, char op) {
for (int i = 0; i < m1.length; i++) {
for (int j = 0; j < m1[0].length; j++)
System.out.print(" " + m1[i][j]);
if (i == m1.length / 2)
System.out.print(" " + op + " ");
else
System.out.print(" ");
for (int j = 0; j < m2.length; j++)
System.out.print(" " + m2[i][j]);
if (i == m1.length / 2)
System.out.print(" = ");
else
System.out.print(" ");
for (int j = 0; j < m3.length; j++)
System.out.print(m3[i][j] + " ");
System.out.println();
}
}
}
public class GenericStack<E> {
private java.util.ArrayList<E> list = new java.util.ArrayList<E>();
public int getSize() {
return list.size();
}
public E peek() {
return list.get(getSize() - 1);
}
public void push(E o) {
list.add(o);
}
public E pop() {
E o = list.get(getSize() - 1);
list.remove(getSize() - 1);
return o;
}
public boolean isEmpty() {
return list.isEmpty();
}
@Override
public String toString() {
return "stack: " + list.toString();
}
}
public class IntegerMatrix extends GenericMatrix<Integer> {
@Override /** Add two integers */
protected Integer add(Integer o1, Integer o2) {
return o1 + o2;
}
@Override /** Multiply two integers */
protected Integer multiply(Integer o1, Integer o2) {
return o1 * o2;
}
@Override /** Specify zero for an integer */
protected Integer zero() {
return 0;
}
}
public class RationalMatrix extends GenericMatrix<Rational> {
@Override /** Add two rational numbers */
protected Rational add(Rational r1, Rational r2) {
return r1.add(r2);
}
@Override /** Multiply two rational numbers */
protected Rational multiply(Rational r1, Rational r2) {
return r1.multiply(r2);
}
@Override /** Specify zero for a Rational number */
protected Rational zero() {
return new Rational(0,1);
}
}
public class SuperWildCardDemo {
public static void main(String[] args) {
GenericStack<String> stack1 = new GenericStack<String>();
GenericStack<Object> stack2 = new GenericStack<Object>();
stack2.push("Java");
stack2.push(2);
stack1.push("Sun");
add(stack1, stack2);
AnyWildCardDemo.print(stack2);
}
public static <T> void add(GenericStack<T> stack1,
GenericStack<? super T> stack2) {
while (!stack1.isEmpty())
stack2.push(stack1.pop());
}
}
import java.util.*;
public class TestArrayListNew {
public static void main(String[] args) {
// Create a list to store cities
ArrayList<String> cityList = new ArrayList<String>();
// Add some cities in the list
cityList.add("London");
cityList.add("New York");
cityList.add("Paris");
cityList.add("Toronto");
cityList.add("Hong Kong");
cityList.add("Singapore");
System.out.println("List size? " + cityList.size());
System.out.println("Is Toronto in the list? " +
cityList.contains("Toronto"));
System.out.println("The location of New York in the list? "
+ cityList.indexOf("New York"));
System.out.println("Is the list empty? " +
cityList.isEmpty()); // Print false
// Insert a new city at index 2
cityList.add(2, "Beijing");
// Remove a city from the list
cityList.remove("Toronto");
// Remove a city at index 1
cityList.remove(1);
// Display London Beijing Paris Hong Kong Singapore
for (int i = 0; i < cityList.size(); i++)
System.out.print(cityList.get(i) + " ");
System.out.println();
// Create a list to store two circles
ArrayList<Circle> list = new ArrayList<Circle>();
// Add a circle and a cylinder
list.add(new Circle(2));
list.add(new Circle(3));
// Display the area of the first circle in the list
System.out.println("The area of the circle? " +
((Circle)list.get(0)).getArea());
}
}
public class TestIntegerMatrix {
public static void main(String[] args) {
// Create Integer arrays m1, m2
Integer[][] m1 = new Integer[][]{{1, 2, 3}, {4, 5, 6}, {1, 1, 1}};
Integer[][] m2 = new Integer[][]{{1, 1, 1}, {2, 2, 2}, {0, 0, 0}};
// Create an instance of IntegerMatrix
IntegerMatrix integerMatrix = new IntegerMatrix();
System.out.println("\nm1 + m2 is ");
GenericMatrix.printResult(
m1, m2, integerMatrix.addMatrix(m1, m2), '+');
System.out.println("\nm1 * m2 is ");
GenericMatrix.printResult(
m1, m2, integerMatrix.multiplyMatrix(m1, m2), '*');
}
}
public class TestRationalMatrix {
public static void main(String[] args) {
// Create two Rational arrays m1 and m2
Rational[][] m1 = new Rational[3][3];
Rational[][] m2 = new Rational[3][3];
for (int i = 0; i < m1.length; i++)
for (int j = 0; j < m1[0].length; j++) {
m1[i][j] = new Rational(i + 1, j + 5);
m2[i][j] = new Rational(i + 1, j + 6);
}
// Create an instance of RationalMatrix
RationalMatrix rationalMatrix = new RationalMatrix();
System.out.println("\nm1 + m2 is ");
GenericMatrix.printResult(
m1, m2, rationalMatrix.addMatrix(m1, m2), '+');
System.out.println("\nm1 * m2 is ");
GenericMatrix.printResult(
m1, m2, rationalMatrix.multiplyMatrix(m1, m2), '*');
}
}
public class WildCardNeedDemo {
public static void main(String[] args ) {
GenericStack<Integer> intStack = new GenericStack<Integer>();
intStack.push(1); // 1 is autoboxed into new Integer(1)
intStack.push(2);
intStack.push(-2);
// Error: System.out.print("The max number is " + max(intStack));
}
/** Find the maximum in a stack of numbers */
public static double max(GenericStack<Number> stack) {
double max = stack.pop().doubleValue(); // initialize max
while (!stack.isEmpty()) {
double value = stack.pop().doubleValue();
if (value > max)
max = value;
}
return max;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment