java 关于stack 的语法解析

来源:互联网 发布:淘宝店铺名字旗舰店 编辑:程序博客网 时间:2024/06/09 22:19

最近偶然开始对stack进行研究,发现这个还蛮简单的,与类似的链表集合不一样的是,stack可以通过直接new stack()创建。

stack数据存储方式为“后进先出”的方式获取【下载地址】  ,例如:

Stack<String> stack = new Stack<String>();stack.add("zhangsan");stack.add("lisi");stack.add("wangwu");stack.add("qianliu");stack.add("zhaoda");int index = stack.search("qianliu");// 寻找对象位置int index1 = stack.search("zhaoda");// 寻找对象位置System.out.println("位置为:"+index+":"+index1);stack.add(3, "孙二娘");String first=stack.firstElement();System.out.println("first="+first);stack.push("王五");System.out.println("top="+stack.lastElement());
</pre><span style="color: rgb(63, 63, 63); line-height: 30px;">在stack中,可以发现最后添加的数据“王五”需要通过lastElement方法获取,如果需要采用search获取位置index,那么可以预计位置为1.</span><p style="padding-top: 0px; padding-bottom: 0px; font-size: 14px; color: rgb(63, 63, 63); line-height: 30px;"></p><p style="padding-top: 0px; padding-bottom: 0px; font-size: 14px; color: rgb(63, 63, 63); line-height: 30px;">stack中对数据已经存在的数据的操作方法都提供了返回参数如:String delete=stack.pop();<br style="padding: 0px;" />stack提供了直接添加入list集合的方法。</p><p style="padding-top: 0px; padding-bottom: 0px; font-size: 14px; color: rgb(63, 63, 63); line-height: 30px;">下面是对stack中数据的遍历:</p><p style="padding-top: 0px; padding-bottom: 0px; font-size: 14px; color: rgb(63, 63, 63); line-height: 30px;"></p><pre code_snippet_id="615026" snippet_file_name="blog_20150309_3_8467051" name="code" class="java" style="font-family: Arial, Helvetica, sans-serif; padding: 5px; border: 1px dotted rgb(170, 170, 170); color: rgb(63, 63, 63); line-height: 30px; background-color: rgb(246, 246, 246);">Iterator<String> it=stack.iterator();while(it.hasNext()){String object=it.next();System.out.print(object+",");}
java支持堆栈中对象元素为null,也可以通过设置setSize(int num)使得数据为null。

最后介绍一下在堆栈中添加list集合:

Stack<String> stack = new Stack<String>();stack.add("zhangsan");stack.add("lisi");stack.add("wangwu");stack.add("qianliu");stack.add("zhaoda");stack.add(null);List<String> list=new ArrayList<String>();list.add("A");list.add("B");list.add("C");stack.addAll(list);System.out.println("size="+stack.size());Iterator<String> it=stack.iterator();while(it.hasNext()){String object=it.next();System.out.print(object+",");}
输出结果为:size=9
zhangsan,lisi,wangwu,qianliu,zhaoda,null,A,B,C,

以上对stack的操作皆来自于对jdk中stack自带方法的处理。并不具备实际的企业开发意义,但是了解堆栈也为以后选择存储数据提供了一个新的方式。

0 0
原创粉丝点击