第一章课后习题1.14
1.14 设计一个泛型类orderedCollection,它存储的Comparable对象的集合(在数组中),以及该集合的当前大小。
提供public方法isEmpty,makeEmpty,insert,remove,findMin和findMax。finfMin和findMax分别返回该集合中最小的和最大T对象的引用(如果该集合为空,则返回null)
package com.algorithm.chapterone; /** * 设计一个泛型类orderedCollection,它存储的Comparable对象的集合(在数组中),以及该集合的当前大小。 * 提供public方法isEmpty,makeEmpty,insert,remove,findMin和findMax。finfMin和findMax分别返回该集合中最小的和最大T对象的引用(如果该集合为空,则返回null) * @author Gao·Rongzheng * */ public class OrderCollection<E> { private static final Comparable[] EMPTY_ELEMENTDATA = {}; private Comparable[] elementData; private int size; public OrderCollection() { elementData = EMPTY_ELEMENTDATA; } public Comparable[] getElement() { return elementData; } public void setElement(Comparable[] elementData) { this.elementData = elementData; size = elementData.length; } public int getSize() { return size; } public boolean isEmpty() { return size == 0; } public void makeEmpty() { elementData = EMPTY_ELEMENTDATA; } public void insert(E e) { Comparable[] temp = new Comparable[size + 1]; System.arraycopy(elementData, 0, temp, 0, size); elementData = temp; size = elementData.length; } public void remove(E e) { Comparable[] temp = new Comparable[size - 1]; for (int i = 0; i < size; i++) { if (elementData[i].equals(e)) { System.arraycopy(elementData, 0, temp, 0, i); System.arraycopy(elementData, i+1, temp, i, size-i-1); break; } } elementData = temp; } public void remove(int index) { Comparable[] temp = new Comparable[size - 1]; for (int i = 0; i < size; i++) { if (i == index) { System.arraycopy(elementData, 0, temp, 0, i); System.arraycopy(elementData, i+1, temp, i, size-i-1); break; } } elementData = temp; } public Comparable findMin() { if (size == 0) return null; int min = 0; for (int i = 0; i < size; i++) { if (elementData[i].compareTo(elementData[min]) <= 0) min = i; } return elementData[min]; } public Comparable findMax() { if (size == 0) return null; int max = 0; for (int i = 0; i < size; i++) { if (elementData[i].compareTo(elementData[max]) > 0) max = i; } return elementData[max]; } public static void main(String[] args) { // TODO Auto-generated method stub } }