Java其他集合

一,Deque

public class DequeDemo {
    /*
     * Deque<E>实现了一个双端队列,既可以添加到队尾也可以添加到队首,既可以从队首获取也可以从队尾获取
     * 扩展至Queue接口
     *总是使用带有last和first的方法
     *避免把null添加到队列 
     */

    public static void main(String[] args) {
        Deque<String> deque = new LinkedList<>();
        deque.offerFirst("yuan");
        deque.offerLast("qi");
        deque.offerFirst("dai");
        
        System.out.println(deque);
        System.out.println(deque.pollFirst());
        System.out.println(deque.pollLast());
        System.out.println(deque);

    }

}

二,Queue

public class QueueTest {
    
    /*
     * Queue<E>实现了一个先进先出的队列
     * LinkedList实现了Queue<E>接口
     * 常用方法
     *         add/offer添加元素
     *         remove/poll获取队列头部元素并删除,后者如果元素为空则返回null,下同
     *         element/peek获取头部元素但不删除
     */

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Queue<Teacher> q = new PriorityQueue<>();//也可以注解添加一个comparactor对象,PriorityQueue<>(new comparactor<Teacher>())
        
        q.add(new Teacher("jack", 23));
        q.add(new Teacher("mary", 33));
        q.add(new Teacher("calve", 21));
        
        //按名字排序输出
        System.out.println(q.poll());
        System.out.println(q.poll());
        System.out.println(q.poll());
    }

    private static void m1() {
        Queue q = new LinkedList();
        Queue<Student> qu = new PriorityQueue<>();
        
        q.offer(12);
        q.offer(true);
        q.offer("yuan");
        q.offer(new Student("jack", 23));
    
        System.out.println(q.poll());
        System.out.println(q.poll());
        System.out.println(q.poll());
        System.out.println(q.poll());
        System.out.println(q.poll());//null
        //System.out.println(q.remove());//java.util.NoSuchElementException
    }

}

猜你喜欢

转载自www.cnblogs.com/noperx/p/11372537.html
今日推荐