`
bdk82924
  • 浏览: 551457 次
  • 性别: 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 栈和堆,Java自动管理栈和堆

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

    关于Java栈与堆的思考-

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

    第25讲谈谈JVM内存区域的划分,哪些区域可能发生OutOfMemoryError1

    第二,Java 虚拟机栈(Java Virtual Machine Stack),早期也叫 Java 栈 第三,堆(Heap),它是 Java 内存管理的核心区

    Java2023年京东最新高级面试题,中级面试题,大汇总.txt

    什么是线程和进程? **进程与线程的区别? 什么是TreeMap 如何停止一个正在运行的线程?... 解释内存中的栈(stack)、堆(heap)和方法区(method area)的用法。 多线程同步有哪几种方法? 什么是自旋?

    Java2023年最新高级面试题及答案,企业真面试题.md 免费下载,不需要积分

    Java2023年最新高级面试题及答案,企业真面试题.md 免费下载,不需要积分 **进程与线程的区别? 什么是TreeMap ... 解释内存中的栈(stack)、堆(heap)和方法区(method area)的用法。 多线程同步有哪几种方法?

    堆和栈总结

    堆栈(stack),堆(heap) Java堆栈 jvm为每个新创建的线程都分配一个堆栈。堆栈以帧为单位保存线程的状态。jvm对堆栈只进行两种操作:以帧为单位的压栈和出栈操作。

    java面试题答案——面试经典

    一、Java基础知识 1.Java有那些基本数据类型,String是不是基本数据类型,他们有何区别。 答案: 8种基本类型 char byte short int ...而其他类型(object)的引用存储在栈(stack)中,他所指的对象存储在堆(heap)中。

    JVM规范--高手总结

    2.5.4 堆(heap)和栈(stack) 20 JAVA垃圾收集器 21 3.1 垃圾收集简史 21 3.2 常见的垃圾收集策略 21 3.2.1 Reference Counting(引用计数) 22 3.2.2 跟踪收集器 22 3.3 JVM的垃圾收集策略 27 3.3.1 Serial Collector ...

    java堆栈的区别 -- 详解

    堆和栈是两个不同的概念 堆和栈的区别 一、预备知识—程序的内存分配 一个由c/C++编译的程序占用的内存分为以下几个部分 1、栈区(stack)— 由编译器自动分配释放 ,存放函数的参数值,局部变量的值等。其...

    java虚拟机参数

    -Xss&lt;size&gt; 设置java线程栈存储(stack)大小。 -Xprof 输出CPU概况数据 -Xrunhprof[:help]|[:&lt;option&gt;=, ...] 执行 Java Virtual Machine Profiler Interface(Java虚拟机探查接口)的堆,CPU,或者...

    JVM面试专题

     3、解释内存中的栈(stack)、堆(heap)和静态区(static area)的用法 4、Perm Space中保存什么数据?会引起OutOfMemory吗? 5、什么是类的加载 6、如何⾃定义⼀个类加载器?你使⽤过哪些或者你在什么场景下需要⼀个⾃...

    Java核心基础+Java中的数据在内存中的存储

    1、内存中的堆(stack)与栈(heap) 2、Java中数据在内存中的存储 基本数据类型的存储 对象的内存模型 包装类数据的存储 String类型数据的存储 数组的内存分配 内存空间的释放 3、Java内存分配中的栈 Java...

    java编程中影响性能的一些点

    1.尽量使用final修饰符。  带有final修饰符的类是不可派生... 调用方法时传递的参数以及在调用中创建的临时变量都保存在栈(Stack)中,速度较快。其他变量,如静态变量,实例变量等,都在堆(Heap)中创建,速度较慢。

    Java虚拟机 JVM 内存结构介绍

    主要介绍Runtime Data Area,包括Java Stack,Native Method Stack, Program Counter Register,Method Area以及Heap 还简要介绍了Runtime Data Area周边的模块,包括Class Loader,Execution Engine,Native ...

    Java2023年最新高级面试题及答案,最新版.md

    **进程与线程的区别? 什么是TreeMap 如何停止一个正在运行的线程? Java 中,编写多线程程序的时候你会遵循哪些最佳... 解释内存中的栈(stack)、堆(heap)和方法区(method area)的用法。 多线程同步有哪几种方法?

    Java2023年最新高级面试题,中级面试题,大汇总,免费直接下载,不需要积分 **进程与线程的区别? 什么是TreeM

    什么是线程和进程? **进程与线程的区别? 什么是TreeMap 如何停止一个正在运行的线程?... 解释内存中的栈(stack)、堆(heap)和方法区(method area)的用法。 多线程同步有哪几种方法? 什么是自旋

    java 面试题 总结

    18、heap和stack有什么区别。 栈是一种线形集合,其添加和删除元素的操作应在同一段完成。栈按照后进先出的方式进行处理。 堆是栈的一个组成元素 19、forward 和redirect的区别 forward是服务器请求资源,服务器直接...

    史上最全Java面试大全

    简答题 22 1.面向对象的特征有哪些方面 22 ...21. 解释内存中的栈(stack)、堆(heap)和静态区(static area)的用法。 29 22.swtich 是否能作用在byte 上,是否能作用在long 上,是否能作用在String上? 31

    java笔试题

    9、解释内存中的栈(stack)、堆(heap)和静态区(static area)的用法。 10、Math.round(11.5) 等于多少?Math.round(-11.5)等于多少? 11、switch 是否能作用在byte 上,是否能作用在long 上,是否能作用在String上? ...

Global site tag (gtag.js) - Google Analytics