Provide Best Programming Tutorials

泛型编程练习题

编写以下方法,返回一个新的ArrayList。新的列表中包含来自原列表中不重复的元素。

public static <E> ArrayList<E> removeDuplicated(ArrayList<E> list)

答案

import java.util.ArrayList;

public class Exercise {
	/** Removes duplicate elements from an array list */
	public static <E extends Comparable<E>> 
			ArrayList<E> removeDuplicates(ArrayList<E> list) {
		for (int i = 0; i < list.size() - 1; i++) {
			for (int j = i + 1; j < list.size(); j++) {
				if (list.get(i).compareTo(list.get(j)) == 0)
					list.remove(j);
			}
		}
		return list;
	} 
}

为线性搜索实现以下泛型方法。

public static <E extends Comparable<E>> int linearSearch(E[] list, E key)            

答案:

public class Exercise {
	/** Method finds the key in a list */
	public static <E extends Comparable<E>>
			int linearSearch(E[] list, E key) {
		for (int i = 0; i < list.length; i++) {
			if (key.compareTo(list[i]) == 0)
				return i;
		}
		return -1;
	}
}

实现下面的方法,返回数组中的最大元素。

public static <E extends Comparable<E>> E max(E[] list)

答案

public class Exercise {
	/** Returns the maximum element in an array */
	public static <E extends Comparable<E>> E max(E[] list) {
		E max = list[0];
		for (int i = 1; i < list.length; i++) {
			if (list[i].compareTo(max) > 0)
				max = list[i];
		}
		return max;
	}
}

编写一个泛型方法,,返回二维数组中的最大元素。

public static <E extends Comparable<E>> E max(E[][] list)

答案

public class Exercise {
	/** Method returns the maximum element in a two-dimensional array */
	public static <E extends Comparable<E>> E max(E[][] list) {
		E max = list[0][0];
		for (int i = 0; i < list.length; i++) {
			for (int j = 0; j < list[i].length; j++) {
				if (list[i][j].compareTo(max) > 0)
					max = list[i][j];
			}
		}
		return max;
	}
}

使用二分查找法实现下面的方法

public static <E extends Comparable<E>> int binarySearch(E[] list, E key)

答案

public class Exercise {

	/** Method performs a binary search 
	  * to find the key in a list */ 
	public static <E extends Comparable<E>>
			int binarySearch(E[] list, E key) {
		int low = 0;
		int high = list.length - 1;

		while (high >= low) {
			int mid = (low + high / 2);
			if (key.compareTo(list[mid]) < 0)
				high = mid - 1;
			else if (key.compareTo(list[mid]) == 0)
				return mid;
			else
				low = mid + 1;
		}

		return -low - 1;
	}
}

编写以下方法,打乱ArrayList。

public static <E> void shuffle(ArrayList<E> list)

答案

import java.util.ArrayList;

public class Exercise_19_08 {
	/** Method shuffles an ArrayList */
	public static <E> void shuffle(ArrayList<E> list) {
		for (int i = 0; i < list.size(); i++) {
			int index = (int)(Math.random() * list.size());
			E temp = list.get(i);
			list.set(i, list.get(index));
			list.set(index, temp);
		}
	}
}

Leave a Reply

Close Menu