All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.feilong.lib.xstream.core.util.FastStack Maven / Gradle / Ivy

Go to download

feilong is a suite of core and expanded libraries that include utility classes, http, excel,cvs, io classes, and much much more.

There is a newer version: 4.0.8
Show newest version
/*
 * Copyright (C) 2004, 2005 Joe Walnes.
 * Copyright (C) 2006, 2007, 2009 XStream Committers.
 * All rights reserved.
 *
 * The software in this package is published under the terms of the BSD
 * style license a copy of which has been included with this distribution in
 * the LICENSE.txt file.
 * 
 * Created on 02. September 2004 by Joe Walnes
 */
package com.feilong.lib.xstream.core.util;

/**
 * An array-based stack implementation.
 * 
 * @author Joe Walnes
 * @author Jörg Schaible
 */
public final class FastStack{

    private Object[] stack;

    private int      pointer;

    public FastStack(int initialCapacity){
        stack = new Object[initialCapacity];
    }

    public Object push(Object value){
        if (pointer + 1 >= stack.length){
            resizeStack(stack.length * 2);
        }
        stack[pointer++] = value;
        return value;
    }

    public void popSilently(){
        stack[--pointer] = null;
    }

    public Object pop(){
        final Object result = stack[--pointer];
        stack[pointer] = null;
        return result;
    }

    public Object peek(){
        return pointer == 0 ? null : stack[pointer - 1];
    }

    public Object replace(Object value){
        final Object result = stack[pointer - 1];
        stack[pointer - 1] = value;
        return result;
    }

    public void replaceSilently(Object value){
        stack[pointer - 1] = value;
    }

    public int size(){
        return pointer;
    }

    public boolean hasStuff(){
        return pointer > 0;
    }

    public Object get(int i){
        return stack[i];
    }

    private void resizeStack(int newCapacity){
        Object[] newStack = new Object[newCapacity];
        System.arraycopy(stack, 0, newStack, 0, Math.min(pointer, newCapacity));
        stack = newStack;
    }

    @Override
    public String toString(){
        StringBuffer result = new StringBuffer("[");
        for (int i = 0; i < pointer; i++){
            if (i > 0){
                result.append(", ");
            }
            result.append(stack[i]);
        }
        result.append(']');
        return result.toString();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy