`
bdk82924
  • 浏览: 563366 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

JAVA实现栈(stack)与堆(heap)

 
阅读更多
Java实现 栈(stack)与堆(heap)

上次写过一个的,下次记得把代码贴上来

待续...

HeapUtil




import java.util.EmptyStackException;
import java.util.Vector;

/**
 * 
 * 模拟 堆,先进先出
 * 
 * @author 
 * @date 2012-6-27 上午02:19:06
 * 
 * @version 1.0
 */
public class HeapUtil<E> extends Vector<E>
{
    /**
     * Creates an empty Stack.
     */
    public HeapUtil()
    {
    }

    /**
     * Pushes an item onto the top of this stack. This has exactly the same
     * effect as: <blockquote>
     * 
     * <pre>
     * addElement(item)
     * </pre>
     * 
     * </blockquote>
     * 
     * @param item
     *            the item to be pushed onto this stack.
     * @return the <code>item</code> argument.
     * @see java.util.Vector#addElement
     */
    public E push(E item)
    {
        addElement(item);

        return item;
    }

    /**
     * Removes the object at the top of this stack and returns that object as
     * the value of this function.
     * 
     * @return The object at the top of this stack (the last item of the
     *         <tt>Vector</tt> object).
     * @exception EmptyStackException
     *                if this stack is empty.
     */
    public synchronized E pop()
    {
        if (empty())
        {
            return null;
        }
        E obj;
        int len = size();

        obj = peek();
        removeElementAt(0);

        return obj;
    }

    /**
     * Looks at the object at the top of this stack without removing it from the
     * stack.
     * 
     * @return the object at the top of this stack (the last item of the
     *         <tt>Vector</tt> object).
     * @exception EmptyStackException
     *                if this stack is empty.
     */
    public synchronized E peek()
    {
        int len = size();

        if (len == 0)
            throw new EmptyStackException();
        return elementAt(0);
    }

    /**
     * Tests if this stack is empty.
     * 
     * @return <code>true</code> if and only if this stack contains no items;
     *         <code>false</code> otherwise.
     */
    public boolean empty()
    {
        return size() == 0;
    }

    /**
     * Returns the 1-based position where an object is on this stack. If the
     * object <tt>o</tt> occurs as an item in this stack, this method returns
     * the distance from the top of the stack of the occurrence nearest the top
     * of the stack; the topmost item on the stack is considered to be at
     * distance <tt>1</tt>. The <tt>equals</tt> method is used to compare
     * <tt>o</tt> to the items in this stack.
     * 
     * @param o
     *            the desired object.
     * @return the 1-based position from the top of the stack where the object
     *         is located; the return value <code>-1</code> indicates that the
     *         object is not on the stack.
     */
    public synchronized int search(Object o)
    {
        int i = lastIndexOf(o);

        if (i >= 0)
        {
            return size() - i;
        }
        return -1;
    }

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = 1224463164541339165L;
}




StackUtil



/**
 * 
 * 栈 先进后出
 * 
 * @author 
 * @date 2012-6-27 上午08:36:52
 * 
 * @param <E>
 * @version 1.0
 */
public class StackUtil<E> extends Vector<E>
{
    /**
     * Creates an empty Stack.
     */
    public StackUtil()
    {
    }

    /**
     * Pushes an item onto the top of this stack. This has exactly the same
     * effect as: <blockquote>
     * 
     * <pre>
     * addElement(item)
     * </pre>
     * 
     * </blockquote>
     * 
     * @param item
     *            the item to be pushed onto this stack.
     * @return the <code>item</code> argument.
     * @see java.util.Vector#addElement
     */
    public E push(E item)
    {
        
        addElement(item);

        return item;
    }

    /**
     * Removes the object at the top of this stack and returns that object as
     * the value of this function.
     * 
     * @return The object at the top of this stack (the last item of the
     *         <tt>Vector</tt> object).
     * @exception EmptyStackException
     *                if this stack is empty.
     */
    public synchronized E pop()
    {
        if (empty())
        {
            return null;
        }
        E obj;
        int len = size();

        obj = peek();
        removeElementAt(len - 1);

        return obj;
    }

    /**
     * Looks at the object at the top of this stack without removing it from the
     * stack.
     * 
     * @return the object at the top of this stack (the last item of the
     *         <tt>Vector</tt> object).
     * @exception EmptyStackException
     *                if this stack is empty.
     */
    public synchronized E peek()
    {
        int len = size();

        if (len == 0)
            throw new EmptyStackException();
        return elementAt(len - 1);
    }

    /**
     * Tests if this stack is empty.
     * 
     * @return <code>true</code> if and only if this stack contains no items;
     *         <code>false</code> otherwise.
     */
    public boolean empty()
    {
        return size() == 0;
    }

    /**
     * Returns the 1-based position where an object is on this stack. If the
     * object <tt>o</tt> occurs as an item in this stack, this method returns
     * the distance from the top of the stack of the occurrence nearest the top
     * of the stack; the topmost item on the stack is considered to be at
     * distance <tt>1</tt>. The <tt>equals</tt> method is used to compare
     * <tt>o</tt> to the items in this stack.
     * 
     * @param o
     *            the desired object.
     * @return the 1-based position from the top of the stack where the object
     *         is located; the return value <code>-1</code> indicates that the
     *         object is not on the stack.
     */
    public synchronized int search(Object o)
    {
        int i = lastIndexOf(o);

        if (i >= 0)
        {
            return size() - i;
        }
        return -1;
    }

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = 1224463164541339165L;
}




Test


import java.util.Arrays;

public class Test
{
    public static void main(String[] args)
    {

        MyVec<Integer> m = new MyVec<Integer>(5);
        m.push(1);
        m.push(2);
        m.push(3);
        m.push(4);
        m.push(5);

        System.out.println(Arrays.asList(m.get()));
        System.out.println(Arrays.asList(m.get()));
        System.out.println(Arrays.asList(m.get()));
        System.out.println(Arrays.asList(m.get()));
        System.out.println(Arrays.asList(m.get()));
        m.push(6);
        m.push(7);
        m.push(8);
        System.out.println(Arrays.asList(m.get()));
        m.push(9);
        m.push(10);
        System.out.println(Arrays.asList(m.get()));
        System.out.println(Arrays.asList(m.get()));
        System.out.println(Arrays.asList(m.get()));
        System.out.println(Arrays.asList(m.get()));
        // while (!m.empty())
        // {
        // System.out.println(m.pop());
        // }
    }

    public static void main1(String[] args)
    {
        System.out.println("StackUtil......");
        StackUtil<String> s = new StackUtil<String>();
        s.push("1");
        s.push("2");
        s.push("3");

        while (!s.empty())
        {
            System.out.println(s.pop());
        }

        System.out.println("HeapUtil......");
        HeapUtil<String> h = new HeapUtil<String>();
        h.push("1");
        h.push("2");
        h.push("3");
        while (!h.empty())
        {
            System.out.println(h.pop());
        }

        System.out.println("QueueUtil......");
        QueueUtil<String> q = new QueueUtil<String>();

        q.add("1");
        q.add("2");
        q.add("3");

        for (int i = 0; i < 10; i++)
        {
            System.out.println(q.next());
        }

    }
}



MyVec 是我写的另外一个例子

特殊的缓存列表 首先有500的缓存大小用来入数据, 10缓存的大小用来读取数据, 读完后指针及指向后面了


import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.List;
import java.util.Vector;

/**
 * 
 * 特殊的缓存列表 首先有500的缓存大小用来入数据, 10缓存的大小用来读取数据, 读完后指针及指向后面了,
 * 
 * @author bdk197431
 * @date 2013-1-14 上午12:41:00
 * 
 * @version 1.0
 */
public class MyVec<E> extends Vector<E>
{
    /**
     * 总大小,缓存的申请大小,如500
     */
    private int maxSize;

    /**
     * 读取缓存的大小,如10,这个值要小于maxSize
     */
    private int readBuffMaxSize = 2;

    /**
     * 指针的指向的id
     */
    private int startIndex;

    /**
     * 指针的指向的endId
     */
    private int endIndex;

    public MyVec()
    {

    }

    public MyVec(int maxSize)
    {
        this.maxSize = maxSize;
    }

    public void debug(String s)
    {

        // System.out.println(s);
    }

    public String toString()
    {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < size(); i++)
        {
            sb.append(elementAt(i));
            if (i != size() - 1)
            {
                sb.append(",");
            }
        }

        sb.append("]");
        return sb.toString();
    }

    public List<E> get()
    {
        debug("get");
        List<E> list = new ArrayList<E>();

        for (int i = startIndex; i < endIndex; i++)
        {

            list.add(get(i));
        }

        if (startIndex + readBuffMaxSize > endIndex)
        {
            startIndex = endIndex;
        } else
        {
            startIndex += readBuffMaxSize;
            endIndex += readBuffMaxSize;
        }

        if (endIndex >= maxSize)
        {
            endIndex = maxSize;
        }
        // readBuffSize = 0;
        debug("start:" + startIndex + " end:" + endIndex);
        debug(this.toString());
        return list;
    }

    public E get(int index)
    {
        if (index >= this.maxSize && index <= endIndex)
        {
            index = index % this.maxSize;
        }

        return elementAt(index);
    }

    /**
     * 
     * 增加 读取缓存的大小
     * 
     * @author
     * @date 2013-1-14 上午03:22:11
     */
    private void addReadBuffSize()
    {
        endIndex++;

        if (endIndex - startIndex > readBuffMaxSize)
        {
            endIndex = startIndex + readBuffMaxSize;
        }

        if (startIndex > 0)
        {
            moveIndex(-1);
        }
    }

    private void moveIndex(int num)
    {
        startIndex += num;
        endIndex += num;
        if (endIndex > maxSize)
        {
            moveIndex(-1);
        }
    }

    /**
     * Pushes an item onto the top of this stack. This has exactly the same
     * effect as: <blockquote>
     * 
     * <pre>
     * addElement(item)
     * </pre>
     * 
     * </blockquote>
     * 
     * @param item
     *            the item to be pushed onto this stack.
     * @return the <code>item</code> argument.
     * @see java.util.Vector#addElement
     */
    public E push(E item)
    {

        debug("push");
        addElement(item);
        if (this.size() > maxSize)
        {
            removeElementAt(0);
            // 指针整体移动一位
            moveIndex(1);

        }
        addReadBuffSize();
        debug("start:" + startIndex + " end:" + endIndex);
        return item;
    }

    /**
     * Removes the object at the top of this stack and returns that object as
     * the value of this function.
     * 
     * @return The object at the top of this stack (the last item of the
     *         <tt>Vector</tt> object).
     * @exception EmptyStackException
     *                if this stack is empty.
     */
    public synchronized E pop()
    {
        if (empty())
        {
            return null;
        }
        E obj;
        int len = size();

        obj = peek();
        removeElementAt(len - 1);

        return obj;
    }

    /**
     * Looks at the object at the top of this stack without removing it from the
     * stack.
     * 
     * @return the object at the top of this stack (the last item of the
     *         <tt>Vector</tt> object).
     * @exception EmptyStackException
     *                if this stack is empty.
     */
    public synchronized E peek()
    {
        int len = size();

        if (len == 0)
            throw new EmptyStackException();
        return elementAt(len - 1);
    }

    /**
     * Tests if this stack is empty.
     * 
     * @return <code>true</code> if and only if this stack contains no items;
     *         <code>false</code> otherwise.
     */
    public boolean empty()
    {
        return size() == 0;
    }

    /**
     * Returns the 1-based position where an object is on this stack. If the
     * object <tt>o</tt> occurs as an item in this stack, this method returns
     * the distance from the top of the stack of the occurrence nearest the top
     * of the stack; the topmost item on the stack is considered to be at
     * distance <tt>1</tt>. The <tt>equals</tt> method is used to compare
     * <tt>o</tt> to the items in this stack.
     * 
     * @param o
     *            the desired object.
     * @return the 1-based position from the top of the stack where the object
     *         is located; the return value <code>-1</code> indicates that the
     *         object is not on the stack.
     */
    public synchronized int search(Object o)
    {
        int i = lastIndexOf(o);

        if (i >= 0)
        {
            return size() - i;
        }
        return -1;
    }

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = 1224463164541339165L;
}



分享到:
评论

相关推荐

    java中堆(heap)和堆栈(stack)有什么区别

    "Java 中堆(heap)和堆栈(stack)的区别" Java 中堆(heap)和堆栈(stack)是两个不同的内存区域,分别用于存储不同的数据类型和对象。堆栈(stack)是 Java 中的一种内存区域,用于存储基本类型的变量和对象的...

    java 栈和堆,Java自动管理栈和堆

    栈(stack)与堆(heap)都是Java用来在Ram中存放数据的地方。与C++不同,Java自动管理栈和堆,程序员不能直接地设置栈或堆。

    堆(heap)与栈(stack)的区别

    堆(heap)与栈(stack)是计算机内存管理中的两种基本数据结构,用于存储程序运行时产生的临时变量。在C语言中,这两种内存区域有非常明确的区分,对于理解程序的内存分配和回收具有重要意义。 首先,栈是一种特殊...

    关于Java栈与堆的思考-

    栈(stack)与堆(heap)都是Java用来在Ram中存放数据的地方。与C++不同,Java自动管理栈和堆,程序员不能直接地设置栈或堆。

    关于Java栈与堆的思考

    关于Java栈与堆的深入解析 Java作为一种广泛使用的编程语言,其内存管理机制是学习者必须掌握的核心概念之一。在Java中,栈(Stack)与堆(Heap)是用于存储数据的主要区域,它们各自承担着不同的职责,对于理解...

    java解决nested exception is java.lang.OutOfMemoryError Java heap space

    Java内存主要分为三个区域:堆(Heap)、栈(Stack)和方法区(Method Area),其中堆是用于存储对象实例的主要区域,当堆空间不足时,就会抛出`OutOfMemoryError: Java heap space`。 1. **调整JVM堆大小**:可以...

    Java中堆内存与栈内存分配浅析

    程序运行时所使用的内存主要分为两类:堆内存(Heap Memory)和栈内存(Stack Memory)。理解这两种内存类型的工作原理及其区别对于优化程序性能、避免内存泄漏等问题至关重要。本文将深入探讨Java中堆内存与栈内存...

    详解java堆和栈

    在Java编程中,理解堆(Heap)和栈(Stack)的概念及其区别对于程序员来说至关重要。本文将深入剖析这两个概念,并探讨它们之间的差异以及如何影响程序的运行。 #### 二、Java中的栈(Stack) Java中的栈主要用于...

    记录java.lang.OutOfMemoryErrorJava heap space的情况.docx

    在Java程序中,`java.lang.OutOfMemoryError: Java heap space` 是一个常见的错误,意味着程序在运行过程中耗尽了JVM分配的堆内存。这个错误通常发生在创建大量对象或者单个对象占用过多内存时。 一、问题描述与...

    java 虚拟机 内存和栈 分析工具 ha456.rar

    Java内存主要分为堆(Heap)、栈(Stack)、方法区(Method Area)、程序计数器(PC Register)和本地方法栈(Native Method Stack)五大部分: 1. **堆**:Java对象主要存储在堆中,它是所有线程共享的一块区域。...

    Java中堆内存和栈内存详解

    本文将深入探讨Java中的两种主要内存区域:堆内存(Heap Memory)和栈内存(Stack Memory)。这两种内存分别承担着不同的角色,对于程序员理解和优化Java程序至关重要。 #### 二、栈内存 栈内存主要用于存储方法的...

    java中的栈(深层了解java虚拟机对对象的内存分布)

    在Java编程语言中,理解栈(stack)和堆(heap)的概念及其工作原理对于深入掌握Java虚拟机(JVM)如何管理内存至关重要。栈和堆都是在RAM中用于存储数据的关键区域,但在功能、使用场景和管理机制上存在显著差异。 #### ...

    区别Java中的堆与栈

    与堆不同,Java的栈用于存储基本类型变量和对象的引用。栈是一种线性的数据结构,遵循先进后出(LIFO)的原则。当函数调用发生时,相应的局部变量和参数会被压入栈中;当函数返回时,这些数据将从栈中弹出,释放所占...

    深入堆与栈 堆与栈的区别

    ##### 示例2:字符串常量池与堆的区别 ```java String s0 = "kvill"; String s1 = "kvill"; String s2 = "kv" + "ill"; System.out.println(s0 == s1); System.out.println(s0 == s2); ``` 这里涉及到字符串常量池...

    java实现内存动态分配

    Java程序运行时,内存分为堆内存(Heap)和栈内存(Stack)。堆内存主要用来存储对象实例和数组,而栈内存主要存储基本类型变量和对象引用。 2. **堆内存分配** 堆内存是Java中的全局共享区域,用于存储所有的...

    深入Java虚拟机中的Stack和Heap

    在Java虚拟机(JVM)中,内存分为两个部分:Stack(栈)和Heap(堆)。Stack是JVM的内存指令区,管理很简单,push一定长度字节的数据或者指令,Stack指针压栈相应的字节位移;pop一定字节长度数据或者指令,Stack...

    Java中堆与栈的内存分配.pdf

    在Java中,内存被分为两部分:堆(Heap)和栈(Stack)。堆是用来存放对象的,它是由Java虚拟机(JVM)管理的。栈是用来存放基本类型的变量和对象的引用变量的,它是由Java编译器管理的。 2. 堆的内存分配 在Java...

Global site tag (gtag.js) - Google Analytics