zoukankan      html  css  js  c++  java
  • 爪哇国新游记之十八----泛型栈类

    import java.lang.reflect.Array;
    
    /**
     * 泛型栈
     *
     * @param <T>
     */
    public class Stack<T>{
        private Class<T> type;// 栈元素所属的类
        private int size;// 栈深度
        private T[] arr;// 用数组存储
        private int top;// 栈顶元素的下标
        
        public Stack(Class<T> type,int size){
            this.type = type;
            this.size=size;
            arr=createArray(size);
            top=-1;
        }
        
        /**
         * 创建数组
         * @param size
         * @return
         */
        @SuppressWarnings("unchecked")    
        private T[] createArray(int size) {    
            return (T[]) Array.newInstance(type, size);    
        }
        
        /**
         * 压栈
         * @param t
         */
        public void push(T t){
            top++;
            arr[top]=t;
        }
        
        /**
         * 出栈
         * @return
         */
        public T pop(){
            T t=arr[top];
            top--;
            return t;
        }
        
        /**
         * 取栈顶元素
         * @return
         */
        public T peek(){
            return arr[top];
        }
        
        /**
         * 判断栈是否为空
         * @return
         */
        public boolean isEmpty(){
            return top==-1;
        }
        
        /**
         * 判断栈是否满了
         * @return
         */
        public boolean isFull(){
            return top==(size-1);
        }
        
        
        public static void main(String[] args){
            Stack<String> s=new Stack<String>(String.class,100);
            s.push("以恒心为良友");
            s.push("以经验为参谋");
            s.push("以小心为兄弟");
            s.push("以希望为哨兵");
            
            while(!s.isEmpty()){
                String str=s.pop();
                System.out.println(str);
            }
            
        }
    }

    输出:

    以希望为哨兵
    以小心为兄弟
    以经验为参谋
    以恒心为良友
  • 相关阅读:
    12月15日,progress_dispaly
    Android studio和Genymotion-VirtualBox的配合使用
    JDK7动态代理源码分析
    跟踪mqttv3源码(二)
    跟踪mqttv3源码(一)
    Spring自定义标签
    Eclipse发布Maven项目到远程服务器
    结合实际项目分析pom.xml
    Maven的安装环境配置
    PHP7新特性
  • 原文地址:https://www.cnblogs.com/heyang78/p/3868187.html
Copyright © 2011-2022 走看看