第十九章程序清单合集——Java语言程序设计进阶篇(黑皮书)

发布于:2024-12-18 ⋅ 阅读:(72) ⋅ 点赞:(0)

目录

程序清单19_1GenericStack

程序清单19_2GenericMethodDemo 

程序清单19_3BoundedTypeDemo 

程序清单19_4GenericSort

程序清单19_5Max

 程序清单19_6MaxUsingGenericType

程序清单19_7wildCardNeedDemo

程序清单19_8AnyWildCardDemo

程序清单19_9SuperWildChardDemo

程序清单19_10GenericMatrix

 程序清单19_11IntegerMatrix

 程序清单19_12RationalMatrix

程序清单13_13Rational(在19_12代码中有引用

程序清单19_13TestIntegerMatrix

程序清单19_14TestRationalMatrix


程序清单19_1GenericStack

package chapter_19;
import java.util.ArrayList;
public class 程序清单19_1GenericStack <E>{
	private ArrayList<E> list = new ArrayList<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();
	}

}

程序清单19_2GenericMethodDemo 

package chapter_19;

public class 程序清单19_2GenericMethodDemo {
	public static void main(String[] args) {
		Integer[] integers = {1, 2, 3, 4,5};
		String[] strings = {"Lodon","Paris", "New york", "Austin"};
		
		程序清单19_2GenericMethodDemo.<Integer>print(integers);
		程序清单19_2GenericMethodDemo.<String>print(strings);
		/*print(integers);
		print(strings);*/
	}
	public static <E> void print(E[] list) {
		for(int i = 0;i < list.length;i++)
			System.out.println(list[i] + " ");
		System.out.println();
	}

}

输出结果

1 2 3 4 5 
Lodon Paris New york Austin 

程序清单19_3BoundedTypeDemo 

package chapter_19;

public class 程序清单19_3BoundedTypeDemo {
	public static void main(String[] args) {
		Rectangle rectangle = new Rectangle();
		Circle circle = new Circle(2);
		
		System.out.println("Same area? ");
	}
	public static <E extends GeometriObject> boolean equalArea(
			E object1,E object2) {
		return object1.getArea() == object2.getArea();
		
	}
}

见程序清单13-4

程序清单19_4GenericSort

package chapter_19;

public class 程序清单19_4GenericSort {
	public static void main(String[] args) {
		 Integer[] intArray = {new Integer(2), new Integer(4),
				 new Integer(3)};
		 
		 Double[] doubleArray = {new Double(3.4),new Double(1.3),
				 new Double(-22.1)};
		 
		 Character[] charArray = {new Character('a'),
				 new Character('J'),new Character('r')};
		 
		 String[] stringArray = {"Tom","Susan","kim"};
		 
		 sort(intArray);
		 sort(doubleArray);
		 sort(charArray);
		 sort(stringArray);
		 
		 System.out.print("Sorted Integer objects: ");
		 printList(intArray);
		 System.out.print("Sorted Double objects: ");
		 printList(doubleArray);
		 System.out.print("Sorted Character objects: ");
		 printList(charArray);
		 System.out.print("Sorted String objects: ");
		 printList(stringArray);
	}
	public static <E extends Comparable<E>> void sort(E[] list) {
		E currentMin;
		int currentMinIndex;
		
		for(int i = 0;i < list.length - 1;i++) {
			currentMin = list[i];
			currentMinIndex = i;
			
			for(int j = i+1;j< list.length;j++) {
				if(currentMin.compareTo(list[j])>0){
					currentMin = list[j];
					currentMinIndex = j;
				}
			}
			if(currentMinIndex != i) {
				list[currentMinIndex] = list[i];
				list[i] = currentMin;
			}
		}
	}
	
	public static void printList(Object[] list) {
		for(int i = 0;i<list.length;i++)
			System.out.print(list[i] + " ");
		System.out.println();
	}

}

程序清单19_5Max

package chapter_19;

public class 程序清单19_5Max {
	public static Comparable max(Comparable o1,Comparable o2) {
		if(o1.compareTo(o2) > 0)
			return o1;
		else
			return o2;
	}
}

 程序清单19_6MaxUsingGenericType

package chapter_19;

public class 程序清单19_6MaxUsingGenericType {
	public static <E extends Comparable<E>> E max(E o1,E o2) {
		if(o1.compareTo(o2)> 0)
			return o1;
		else 
			return o2;
		
	}

}

程序清单19_7wildCardNeedDemo

package chapter_19;

public class 程序清单19_7wildCardNeedDemo {
	public static void main(String[] args) {
		程序清单19_1GenericStack<Integer> intStack = new 程序清单19_1GenericStack<Integer>();
		intStack.push(1);
		intStack.push(2);
		intStack.push(-2);
		
		System.out.println("The max number is "+max(intStack));
	}
	//public static double max(程序清单19_1GenericStack<Number>stack) {intStack不是GenericStack<Number>的实例,所以这行代码会出错
	public static double max(程序清单19_1GenericStack<Integer>stack) {
		double max = stack.pop().doubleValue();
		while(!stack.isEmpty()) {
			double value = stack.pop().doubleValue();
			if(value > max)
				max = value;
		}
		return max;
	}

}

 输出结果

The max number is 2.0

程序清单19_8AnyWildCardDemo

package chapter_19;

public class 程序清单19_8AnyWildCardDemo {
	public static void main(String[] args) {
		程序清单19_1GenericStack<Integer> intStack = new 程序清单19_1GenericStack<>();
		intStack.push(1);
		intStack.push(2);
		intStack.push(-2);
		
		print(intStack);
	}
	public static void print(程序清单19_1GenericStack<?> stack) {
		while(!stack.isEmpty()) {
			System.out.print(stack.pop() + " ");
		}
	}
	
}

程序清单19_9SuperWildChardDemo

package chapter_19;

public class 程序清单19_9SuperWildChardDemo {
	public static void main(String[] args) {
		程序清单19_1GenericStack<String> stack1 = new 程序清单19_1GenericStack<>();
		程序清单19_1GenericStack<Object> stack2 = new 程序清单19_1GenericStack<>();
		stack2.push("Java");
		stack2.push(2);;
		stack1.push("Sun");
		
		add(stack1, stack2);
		程序清单19_8AnyWildCardDemo.print(stack2);
		
	}
	public static <T> void add(程序清单19_1GenericStack<T> stack1,
			程序清单19_1GenericStack<? super T> stack2) {
		while (!stack1.isEmpty()) 
			stack2.push(stack1.pop());
	}

}

 输出结果

Sun 2 Java 

程序清单19_10GenericMatrix

package chapter_19;

public abstract class 程序清单19_10GenericMatrix <E extends Number>{
	protected abstract E add(E o1,E o2);
	protected abstract E multiply(E o1,E o2);
	protected abstract E zero();
	
	public E[][] addMatrix(E[][] matrix1,E[][] matrix2){
		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];
		
		for(int i = 0;i < result[i].length;i++) {
			for(int j = 0;j < result[i].length;j++) {
				result[i][j] = add(matrix1[i][j],matrix2[i][j]);
			}
		}
		return result;
	}
	public E[][] multiplyMatrix(E[][] matrix1,E[][] matrix2){
		if(matrix1[0].length != matrix2.length) {
			throw new RuntimeException(
					"The matrices do no have compatible size");
		}
		E[][] result = 
				(E[][])new Number[matrix1.length][matrix2[0].length];
		
		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;
	}
	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();
		}
	}
}

 程序清单19_11IntegerMatrix

package chapter_19;

public class 程序清单19_11IntegerMatrix extends 程序清单19_10GenericMatrix<Integer>{
	@Override
	protected Integer add(Integer o1,Integer o2) {
		return o1 + o2;
	}
	
	@Override
	protected Integer multiply(Integer o1, Integer o2) {
		return o1 * o2;
	}
	
	@Override
	protected Integer zero() {
		return 0;
	}

}

 程序清单19_12RationalMatrix

package chapter_19;

public class 程序清单19_12RationalMatrix extends 程序清单19_10GenericMatrix<程序清单13_13Rational>{
	@Override
	protected 程序清单13_13Rational add(程序清单13_13Rational r1,程序清单13_13Rational r2) {
		return r1.add(r2);
	}
	
	@Override 
	protected 程序清单13_13Rational multiply(程序清单13_13Rational r1,程序清单13_13Rational r2) {
		return r1.multiply(r2);
	}
	@Override
	protected 程序清单13_13Rational zero() {
		return new 程序清单13_13Rational(0,1);
	}
}

程序清单13_13Rational(在19_12代码中有引用

package chapter_19;

public class 程序清单13_13Rational extends Number implements Comparable<程序清单13_13Rational>{
	private long numerator = 0;
	private long denominator = 1;
	
	public 程序清单13_13Rational() {
		this(0,1);
	}
	public 程序清单13_13Rational(long numerator,long denominator) {
		long gcd = gcd(numerator,denominator);
		this.numerator = ((denominator > 0)?1:-1)*numerator / gcd;
		this.denominator = Math.abs(denominator) / gcd;
	}
	
	private static long gcd(long n,long d) {
		long n1 =Math.abs(n);
		long n2 = Math.abs(d);
		int gcd = 1;
		
		for(int k = 1;k <= n1&&k <= n2;k++) {
			if(n1 %k == 0&&n2 % k == 0)
			gcd = k;
		}
		return gcd;
	}
	public long getNumerator() {
		return numerator;
	}
	public long getDenominator() {
		return denominator;
	}
	public 程序清单13_13Rational add(程序清单13_13Rational secondRational) {
		long n = numerator * secondRational.getDenominator()+
				denominator*secondRational.getNumerator();
		long d = denominator * secondRational.getDenominator();
		
		return new 程序清单13_13Rational(n,d);
	}
	public 程序清单13_13Rational subtract(程序清单13_13Rational secondRational) {
		long n = numerator * secondRational.getDenominator()
				- denominator * secondRational.getNumerator();
		long d = denominator * secondRational.getDenominator();
		
		return new 程序清单13_13Rational(n,d);
	}
	
	public 程序清单13_13Rational multiply(程序清单13_13Rational secondRational) {
		long n = numerator * secondRational.getNumerator();
		long d = denominator * secondRational.getDenominator();
		return new 程序清单13_13Rational(n,d);
	}
	public 程序清单13_13Rational divide(程序清单13_13Rational secondRational) {
		long n = numerator * secondRational.getDenominator();
		long d = denominator * secondRational.numerator;
		return new 程序清单13_13Rational(n,d);
	}
	
	@Override
	public String toString() {
		if(denominator == 1)
			return numerator +"";
		else
			return numerator + "/" + denominator;
	}
	@Override
	public boolean equals(Object other) {
		if((this.subtract((程序清单13_13Rational)(other))).getNumerator() == 0)
			return true;
		else
			return false;
	}
	
	@Override
	public int intValue() {
		return (int)doubleValue();
	}
	
	@Override
	public float floatValue() {
		return (float)doubleValue();
	}
	@Override
	public double doubleValue() {
		return numerator * 1.0/denominator;
	}
	@Override
	public long longValue() {
		return (long)doubleValue();
	}
	
	@Override
	public int compareTo(程序清单13_13Rational o) {
		if(this.subtract(o).getNumerator() > 0)
			return 1;
		else if(this.subtract(o).getNumerator() < 0)
			return -1;
		else 
			return 0;
	}
}

程序清单19_13TestIntegerMatrix

 package chapter_19;

public class 程序清单19_13TestIntegerMatrix {
	public static void main(String[] args) {
		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}};
		
		程序清单19_11IntegerMatrix integerMatrix = new 程序清单19_11IntegerMatrix();
		System.out.println("\nm1 + m2 is ");
		程序清单19_10GenericMatrix.printResult(m1, m2, 
				integerMatrix.addMatrix(m1, m2), '+');
		
		System.out.println("\nm1 * m2 is ");
		程序清单19_10GenericMatrix.printResult(m1, m2, 
				integerMatrix.multiplyMatrix(m1, m2), '*');
	}
}

输出结果

m1 + m2 is 
 1 2 3     1 1 1    2 3 4 
 4 5 6 +  2 2 2 = 6 7 8 
 1 1 1     0 0 0    1 1 1 

m1 * m2 is 
 1 2 3     1 1 1    5 5 5 
 4 5 6 *  2 2 2 = 14 14 14 
 1 1 1     0 0 0    3 3 3 

程序清单19_14TestRationalMatrix

package chapter_19;

public class 程序清单19_14TestRationalMatrix {
	public static void main(String[] args) {
		程序清单13_13Rational[][] m1 = new 程序清单13_13Rational[3][3];
		程序清单13_13Rational[][] m2 = new 程序清单13_13Rational[3][3];
		
		for(int i = 0;i < m1.length;i++) {
			for(int j = 0;j < m1[0].length;j++) {
				m1[i][j] = new 程序清单13_13Rational(i+1,j+5);
				m2[i][j] = new 程序清单13_13Rational(i+1,j+6);
			}
		}
		程序清单19_12RationalMatrix rationalMatrix = new 程序清单19_12RationalMatrix();
		System.out.println("\nm1 + m2 + is ");
		程序清单19_10GenericMatrix.printResult(m1, m2,
				rationalMatrix.addMatrix(m1, m2), '+');
		
		System.out.println("\nm1 * m2 is ");
		程序清单19_10GenericMatrix.printResult(m1, m2,
				rationalMatrix.multiplyMatrix(m1, m2), '*');
		
	}
}

 输出结果

m1 + m2 + is 
 1/5 1/6 1/7     1/6 1/7 1/8    11/30 13/42 15/56 
 2/5 1/3 2/7 +  1/3 2/7 1/4 = 11/15 13/21 15/28 
 3/5 1/2 3/7     1/2 3/7 3/8    11/10 13/14 45/56 

m1 * m2 is 
 1/5 1/6 1/7     1/6 1/7 1/8    101/630 101/735 101/840 
 2/5 1/3 2/7 *  1/3 2/7 1/4 = 101/315 202/735 101/420 
 3/5 1/2 3/7     1/2 3/7 3/8    101/210 101/245 101/280 


网站公告

今日签到

点亮在社区的每一天
去签到