原文链接:https://github.com/Snailclimb/JavaGuide
0.0.1. 泛型的实际应用:实现最小值函数 自己设计一个泛型的获取数组最小值的函数.并且这个方法只能接受Number的子类并且实现了Comparable接口。
1 2 3 4 5 6 7 8 9 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; }
测试:
1 2 3 int minInteger = min(new Integer[]{1 , 2 , 3 });double minDouble = min(new Double[]{1.2 , 2.2 , -1 d});String typeError = min(new String[]{"1" ,"3" });
0.0.2. 使用数组实现栈 自己实现一个栈,要求这个栈具有push()
、pop()
(返回栈顶元素并出栈)、peek()
(返回栈顶元素不出栈)、isEmpty()
、size()
这些基本的方法。
提示:每次入栈之前先判断栈的容量是否够用,如果不够用就用Arrays.copyOf()
进行扩容;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 public class MyStack { private int [] storage; private int capacity; private int count; private static final int GROW_FACTOR = 2 ; public MyStack () { this .capacity = 8 ; this .storage=new int [8 ]; this .count = 0 ; } public MyStack (int initialCapacity) { if (initialCapacity < 1 ) throw new IllegalArgumentException("Capacity too small." ); this .capacity = initialCapacity; this .storage = new int [initialCapacity]; this .count = 0 ; } public void push (int value) { if (count == capacity) { ensureCapacity(); } storage[count++] = value; } private void ensureCapacity () { int newCapacity = capacity * GROW_FACTOR; storage = Arrays.copyOf(storage, newCapacity); capacity = newCapacity; } private int pop () { if (count == 0 ) throw new IllegalArgumentException("Stack is empty." ); count--; return storage[count]; } private int peek () { if (count == 0 ){ throw new IllegalArgumentException("Stack is empty." ); }else { return storage[count-1 ]; } } private boolean isEmpty () { return count == 0 ; } private int size () { return count; } }
验证
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 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()); System.out.println(myStack.size()); for (int i = 0 ; i < 8 ; i++) { System.out.println(myStack.pop()); } System.out.println(myStack.isEmpty()); myStack.pop();