一些重要的Java程序设计题

泛型的实际应用

实现最小值函数

自己设计一个泛型的获取数组最小值的函数.并且这个方法只能接受Number的子类并且实现了Comparable接口。

  1. //注意:Number并没有实现Comparable
  2. private static <T extends Number & Comparable<? super T>> T min(T[] values) {
  3. if (values == null || values.length == 0) return null;
  4. T min = values[0];
  5. for (int i = 1; i < values.length; i++) {
  6. if (min.compareTo(values[i]) > 0) min = values[i];
  7. }
  8. return min;
  9. }

测试:

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

数据结构

使用数组实现栈

自己实现一个栈,要求这个栈具有push()pop()(返回栈顶元素并出栈)、peek() (返回栈顶元素不出栈)、isEmpty()size()这些基本的方法。

提示:每次入栈之前先判断栈的容量是否够用,如果不够用就用Arrays.copyOf()进行扩容;

  1. public class MyStack {
  2. private int[] storage;//存放栈中元素的数组
  3. private int capacity;//栈的容量
  4. private int count;//栈中元素数量
  5. private static final int GROW_FACTOR = 2;
  6. //TODO:不带初始容量的构造方法。默认容量为8
  7. public MyStack() {
  8. this.capacity = 8;
  9. this.storage=new int[8];
  10. this.count = 0;
  11. }
  12. //TODO:带初始容量的构造方法
  13. public MyStack(int initialCapacity) {
  14. if (initialCapacity < 1)
  15. throw new IllegalArgumentException("Capacity too small.");
  16. this.capacity = initialCapacity;
  17. this.storage = new int[initialCapacity];
  18. this.count = 0;
  19. }
  20. //TODO:入栈
  21. public void push(int value) {
  22. if (count == capacity) {
  23. ensureCapacity();
  24. }
  25. storage[count++] = value;
  26. }
  27. //TODO:确保容量大小
  28. private void ensureCapacity() {
  29. int newCapacity = capacity * GROW_FACTOR;
  30. storage = Arrays.copyOf(storage, newCapacity);
  31. capacity = newCapacity;
  32. }
  33. //TODO:返回栈顶元素并出栈
  34. private int pop() {
  35. count--;
  36. if (count == -1)
  37. throw new IllegalArgumentException("Stack is empty.");
  38. return storage[count];
  39. }
  40. //TODO:返回栈顶元素不出栈
  41. private int peek() {
  42. if (count == 0){
  43. throw new IllegalArgumentException("Stack is empty.");
  44. }else {
  45. return storage[count-1];
  46. }
  47. }
  48. //TODO:判断栈是否为空
  49. private boolean isEmpty() {
  50. return count == 0;
  51. }
  52. //TODO:返回栈中元素的个数
  53. private int size() {
  54. return count;
  55. }
  56. }

验证

  1. MyStack myStack = new MyStack(3);
  2. myStack.push(1);
  3. myStack.push(2);
  4. myStack.push(3);
  5. myStack.push(4);
  6. myStack.push(5);
  7. myStack.push(6);
  8. myStack.push(7);
  9. myStack.push(8);
  10. System.out.println(myStack.peek());//8
  11. System.out.println(myStack.size());//8
  12. for (int i = 0; i < 8; i++) {
  13. System.out.println(myStack.pop());
  14. }
  15. System.out.println(myStack.isEmpty());//true
  16. myStack.pop();//报错:java.lang.IllegalArgumentException: Stack is empty.