廖雪峰Java5Java集合-5Queue-1使用Queue
Queue特性和基本方法
Queue
Java中LinkedList实现了Queue
- 获取队列长度size()
- 添加元素到队尾boolean add(E e)/boolean offer(E e)
- 获取队列头部元素并删除 E remove()/E poll()
- 获取队列头部元素但不删除E element()/E peek()
为什么添加和获取元素提供2组方法?
当添加或获取元素失败时,1个抛出异常,另1个返回false或null。
throw Exception | 返回false或null | |
---|---|---|
添加元素到队尾 | add(E e) | boolean offer(E e) |
取对首元素并删除 | E remove() | E poll() |
取队首元素但不删除 | E element() | E peek() |
失败场景示例:
- 1.如果队列有一个最大长度限制,可能添加失败
//演示代码Queue q = ...;
if (q.offer("abc")){
//添加成功
}else{
//添加失败
}
- 2.如果队列是空队列,队首元素获取失败。
//演示代码Queue q = ...;
if (q.isEmpty()){
//不能获取队首元素
}else{
//可以获取队首元素
}
示例
Person.java
public class Person { private String name;
private int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
@Override
public String toString(){
return "(Person:"+name+","+age+")";
}
public boolean equals(Object o){
if (this == o){
return true;
}
if (o instanceof Person){
Person p = (Person) o;
return Objects.equals(p.name,this.name) && p.age == this.age;
}
return false;
}
}
Main.java
public class Main { public static void main(String[] args) throws IOException {
Queue<Person> queue = new LinkedList<>();
queue.offer(new Person("小明",12));
queue.offer(new Person("小红",12));
queue.offer(new Person("小军",12));
System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.poll());
}
}
```#java
public class Main {
public static void main(String[] args) throws IOException {
Queue
queue.offer(new Person("小明",12));
queue.offer(new Person("小红",12));
queue.offer(new Person("小军",12));
System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.remove());
}
}
```
```#java
public class Main {
public static void main(String[] args) throws IOException {
Queue
queue.offer(new Person("小明",12));
queue.offer(new Person("小红",12));
queue.offer(new Person("小军",12));
System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.poll());
//改写代码,先判断队列是否为空
if (!queue.isEmpty()) {
System.out.println(queue.remove());
}
}
}
```
总结
- Queue
实现一个FIFO的队列 - add/offer将元素添加到队尾
- remove/poll从队首获取元素并删除
- element/peek从队首获取元素但不删除
- 避免把null添加到队列
以上是 廖雪峰Java5Java集合-5Queue-1使用Queue 的全部内容, 来源链接: utcz.com/z/391219.html