JAVA语言程序设计(进阶篇)第十版

十九. 泛型

什么是泛型
答:数据类型参数化。

泛型有什么作用?
答:1.编译时检测出错误。
2.提高可扩展性。

泛型类型一定是除了八种基本类型之外的引用类型

Case 19.1 GenericStack.java

import java.util.ArrayList;

public class GenericStack<E> {
	private ArrayList<E> list = new ArrayList<>();

	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);
		return o;
	}

	public boolean isEmpty() {
		return list.isEmpty();
	}

	@Override
	public String toString() {
		return "stack:" + list.toString();
	}
}

Case 19.2 GenericMethodDemo.java

public class GenericMEthodDemo {
	public static void main(String[] args) {
		Integer[] integers = { 1, 2, 3, 4, 5 };
		String[] strings = { "London", "Paris", "New York", "Austin" };
		GenericMEthodDemo.<Integer>print(integers);
		GenericMEthodDemo.<String>print(strings);
	}

	public static <E> void print(E[] list) {
		for (int i = 0; i < list.length; i++)
			System.out.print(list[i] + " ");
		System.out.println();
	}
}

Case 19.3 BoundedTypeDemo.java

public class BoundedTypeDemo {
	public static void main(String[] args) {
		Rectangle rectangle = new Rectangle(2, 2);
		Circle circle = new Circle(2);

		System.out.println("Same area?" + equalArea(rectangle, circle));
	}

	public static <E extends Geometricobject> boolean equalArea(E object1, E object2) {
		return object1.getArea() == object2.getArea();
	}
}

Case 19.4 GenericSort.java



public class  GenericSort {
	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 = { 'a', 'Z', 'b' };
		String[] stringArray = { "niba", "nima", "nierzi" };

		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++) {
			// find the minimum in the list [ i+1..list.length-2]
			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();
	}
}

你可能感兴趣的:(JAVA语言程序设计(进阶篇)第十版)