天天看點

Java程式設計題

實作最小值函數(泛型的實際應用)

自己設計一個泛型的擷取數組最小值的函數.并且這個方法隻能接受Number的子類并且實作了Comparable接口。

//注意:Number并沒有實作Comparable
private static <T extends Number & Comparable<? super T>> T min(T[] values) {
    if (values == null || values.length == 0) return null;
    T min = values[0];
    for (int i = 1; i < values.length; i++) {
        if (min.compareTo(values[i]) > 0) min = values[i];
    }
    return min;
}
           

測試:

int minInteger = min(new Integer[]{1, 2, 3});//result:1
double minDouble = min(new Double[]{1.2, 2.2, -1d});//result:-1d
String typeError = min(new String[]{"1","3"});//報錯
           

使用數組實作棧(資料結構)

自己實作一個棧,要求這個棧具有push()、pop()(傳回棧頂元素并出棧)、peek() (傳回棧頂元素不出棧)、isEmpty()、size()這些基本的方法。

提示:每次入棧之前先判斷棧的容量是否夠用,如果不夠用就用Arrays.copyOf()進行擴容;

public class MyStack {
    private int[] storage;//存放棧中元素的數組
    private int capacity;//棧的容量
    private int count;//棧中元素數量
    private static final int GROW_FACTOR = 2;

    //TODO:不帶初始容量的構造方法。預設容量為8
    public MyStack() {
        this.capacity = 8;
        this.storage=new int[8];
        this.count = 0;
    }

    //TODO:帶初始容量的構造方法
    public MyStack(int initialCapacity) {
        if (initialCapacity < 1)
            throw new IllegalArgumentException("Capacity too small.");

        this.capacity = initialCapacity;
        this.storage = new int[initialCapacity];
        this.count = 0;
    }

    //TODO:入棧
    public void push(int value) {
        if (count == capacity) {
            ensureCapacity();
        }
        storage[count++] = value;
    }

    //TODO:確定容量大小
    private void ensureCapacity() {
        int newCapacity = capacity * GROW_FACTOR;
        storage = Arrays.copyOf(storage, newCapacity);
        capacity = newCapacity;
    }

    //TODO:傳回棧頂元素并出棧
    private int pop() {
        count--;
        if (count == -1)
            throw new IllegalArgumentException("Stack is empty.");

        return storage[count];
    }

    //TODO:傳回棧頂元素不出棧
    private int peek() {
        if (count == 0){
            throw new IllegalArgumentException("Stack is empty.");
        }else {
            return storage[count-1];
        }
    }

    //TODO:判斷棧是否為空
    private boolean isEmpty() {
        return count == 0;
    }

    //TODO:傳回棧中元素的個數
    private int size() {
        return count;
    }

}
           

驗證

MyStack myStack = new MyStack(3);
myStack.push(1);
myStack.push(2);
myStack.push(3);
myStack.push(4);
myStack.push(5);
myStack.push(6);
myStack.push(7);
myStack.push(8);System.out.println(myStack.peek());//8System.out.println(myStack.size());//8for (int i = 0; i < 8; i++) {
    System.out.println(myStack.pop());
}System.out.println(myStack.isEmpty());//true
myStack.pop();//報錯:java.lang.IllegalArgumentException: Stack is empty.