java 中的Stack、Queue、Deque

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gao1440156051/article/details/70915808

1.Stack

java集合框架中没有Stack接口,仅仅有java早期遗留下来的一个Stack类。

Deque stack = new ArrayDeque();

public Stack extends Vector

因为集成自Vector,所以Stack类是同步的,效率不高。官方一般建议这样使用ArrayDeque代替Stack

Java.util.Stack

2.Queue接口


简单介绍几个方法的区别:

offer,add区别:

一些队列有大小限制,因此如果想在一个满的队列中加入一个新项,多出的项就会被拒绝。

这时新的 offer 方法就可以起作用了。它不是对调用 add() 方法抛出一个 unchecked 异常,而只是得到由 offer() 返回的 false。 

 

poll,remove区别:

remove() 和 poll() 方法都是从队列中删除第一个元素。remove() 的行为与 Collection 接口的版本相似,

但是新的 poll() 方法在用空集合调用时不是抛出异常,只是返回 null。因此新的方法更适合容易出现异常条件的情况。

 

peek,element区别:

element() 和 peek() 用于在队列的头部查询元素。与 remove() 方法类似,在队列为空时, element() 抛出一个异常,而 peek() 返回 null


3. Deque接口

Deque是Queue的子接口。
Deque有两个比较重要的类:ArrayDeque和LinkedList
建议 使用栈时,用ArrayDeque的push和pop方法;
  使用队列时,使用ArrayDeque的add和remove方法。

4.优先队列PriorityQueue

如果不提供Comparator的话,优先队列中元素默认按自然顺序排列,也就是数字默认是小的在队列头,字符串则按字典序排列。

import java.util.Comparator;  
import java.util.PriorityQueue;  
import java.util.Queue;  
  
public class Main {  
    private String name;  
    private int population;  
    public Main(String name, int population)  
    {  
        this.name = name;  
        this.population = population;  
    }  
    public String getName()  
    {  
         return this.name;  
    }  
  
    public int getPopulation()  
    {  
         return this.population;  
    }  
    public String toString()  
    {  
         return getName() + " - " + getPopulation();  
    } 
    
    public static void main(String args[])  
    {  
        Comparator<Main> OrderIsdn =  new Comparator<Main>(){  
			@Override
			public int compare(Main o1, Main o2) {
				int numbera = o1.getPopulation();  
                int numberb = o2.getPopulation();
				return Integer.compare(numbera, numberb);
			}  
        };  
        Queue<Main> priorityQueue =  new PriorityQueue<Main>(11,OrderIsdn);  
          
        Main t1 = new Main("t1",1);  
        Main t3 = new Main("t3",3);  
        Main t2 = new Main("t2",2);  
        Main t4 = new Main("t4",0);  
        priorityQueue.add(t1);  
        priorityQueue.add(t3);  
        priorityQueue.add(t2);  
        priorityQueue.add(t4);  
        System.out.println(priorityQueue.poll().toString());  
    }  
}  
 
 

结果 t4 - 0





offer,add区别:

一些队列有大小限制,因此如果想在一个满的队列中加入一个新项,多出的项就会被拒绝。

这时新的 offer 方法就可以起作用了。它不是对调用 add() 方法抛出一个 unchecked 异常,而只是得到由 offer() 返回的 false。 

 

poll,remove区别:

remove() 和 poll() 方法都是从队列中删除第一个元素。remove() 的行为与 Collection 接口的版本相似,

但是新的 poll() 方法在用空集合调用时不是抛出异常,只是返回 null。因此新的方法更适合容易出现异常条件的情况。

 

peek,element区别:

element() 和 peek() 用于在队列的头部查询元素。与 remove() 方法类似,在队列为空时, element() 抛出一个异常,而 peek() 返回 null

猜你喜欢

转载自blog.csdn.net/gao1440156051/article/details/70915808
今日推荐