java 栈类_java集合类——Stack栈类与Queue队列

今日走读代码时,遇到stack栈类,特查看java的API文档,总结如下:

Stack继承Vector类,它通过五个操作对类 Vector 进行了扩展。 栈是 后进先出的。 栈提供了通常的 push 和 pop 操作,以及取堆栈顶点的 peek 方法、测试堆栈是否为空的 empty 方法、在堆栈中查找项并确定到堆栈顶距离的 search 方法。

方法摘要

boolean

E item)

把项压入堆栈顶部。

int

现附上例子,后续继续总结

/**

* @作者 whs

* @创建日期 2015年2月4日

* @版本 V 1.0

*/

package thread.pool;

import java.util.Stack;

public class StackExam {

public static void main(String[] args) {

Stack stack = new Stack();

System.out.println("now the satck is "+isEmpty(stack));

stack.push("1");

stack.push("2");

stack.push("3");

stack.push("4");

stack.push("5");

stack.push("6");

System.out.println("now the stack is "+isEmpty(stack));

System.out.println(stack.peek());//查看堆栈顶部的对象,并返回该对象,但不从堆栈中移除它。

System.out.println(stack.pop());

System.out.println(stack.pop());

System.out.println(stack.search("3"));//,此方法返回最近的目标对象距堆栈顶部出现位置到堆栈顶部的距离;

}

public static String isEmpty(Stack stack){

return stack.empty() ? "empty":"not empty";

}

}

输出为:

now the satck is empty

now the stack is not empty

6

6

5

2

接口 Queue队列:

Queue接口与List、Set同一级别,都是继承了Collection接口。LinkedList实现了Queue接 口。Queue接口窄化了对LinkedList的方法的访问权限(即在方法中的参数类型如果是Queue时,就完全只能访问Queue接口所定义的方法 了,而不能直接访问 LinkedList的非Queue的方法),以使得只有恰当的方法才可以使用。BlockingQueue 继承了Queue接口。

队列通常(但并非一定)以 FIFO(先进先出)的方式排序各个元素。不过优先级队列和 LIFO 队列(或堆栈)例外,前者根据提供的比较器或元素的自然顺序对元素进行排序,后者按 LIFO(后进先出)的方式对元素进行排序。无论使用哪种排序方式,队列的头 都是调用 remove() 或 poll() 所移除的元素。在 FIFO 队列中,所有的新元素都插入队列的末尾。其他种类的队列可能使用不同的元素放置规则。每个 Queue 实现必须指定其顺序属性。

方法摘要

boolean

true,如果当前没有可用的空间,则抛出 IllegalStateException。

boolean

add(E),后者可能无法插入元素,而只是抛出一个异常。

null。

null。

Queue使用时要尽量避免Collection的add()和remove()方法,而是要使用offer()来加入元素,使用poll()来获取并移出元素。它们的优点是通过返回值可以判断成功与否,add()和remove()方法在失败的时候会抛出异常。 如果要使用前端而不移出该元素,使用element()或者peek()方法。

注意:poll和peek方法出错进返回null。因此,向队列中插入null值是不合法的。

例子:

Queue queue=new LinkedList();

queue.offer("Hello");

queue.offer("World!");

queue.offer("你好?");

System.out.println(queue.size());

for(String str:queue){

System.out.printf(str + " ");

}

System.out.printf("\n");

System.out.println(queue.size());

String str;

while((str=queue.poll()) != null){

System.out.printf(str + " ");

}

System.out.println();

System.out.println(queue.size());

输出结果:

3

Hello World ! 你好?

3

Hello World ! 你好?

0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值