Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
How do I get a PriorityQueue to sort on what I want it to sort on? Added: And is there a difference between the offer and add methods?
What is the difference between Collection and List in Java? When and which I should use?
I'm writing a Mandelbrot fractal viewer, and I would like to implement color cycling in a smart way. Given an image, I would like to modify its IndexColorModel. As far as I can tell, there's no way to modify an IndexColorModel, and there's no way to give an image a new IndexColorModel. In fact, I think there's no way to extract its color model or image data. It seems that the only solution is...
I currently have the GUI made for a simon says game, the only problem I'm having is implementing the game logic (my current code will generate a sequence and display user input, but won't save the generated sequence, or compare it to the input). I know I have to use either a queue or a stack, but I can't figure out how to implement either of these to make a working game. Can someone please hel...
We're currently writing an application for which IT has already purchased hardware for. Their approach was to buy big hardware on which we would deploy. In order to add more processing, they plan on adding additional servers with identical software. In order to accomodate this design, we are using Terracotta to provide the ability to run multiple JVM's as though it was one large one. Regardless...
Is it possible to add elements to a collection while iterating over it? More specifically, I would like to iterate over a collection, and if an element satisfies a certain condition I want to add some other elements to the collection, and make sure that these added elements are iterated over as well. (I realise that this could lead to an unterminating loop, but I'm pretty sure it won't in my ...
My engine is executing 1,000,000 of simulations on X deals. During each simulation, for each deal, a specific condition may be verified. In this case, I store the value (which is a double) into an array. Each deal will have its own list of values (i.e. these values are indenpendant from one deal to another deal). At the end of all the simulations, for each deal, I run an algorithm on his List&...
I have two processes (producer/consumer). The first one puts elements in a Collection, the second one reads them. I want the second process not to read every individual element, but wait until: There are at least N elements in the collection OR The last element was received T seconds ago. Is there any Collection in Java 5+ that allows this kind of behaviour? I was thinking about an imple...
Please Note: I am not "looking for teh codez" - just ideas for algorithms to solve this problem. This IS a homework assignment. I thought I was in the home stretch, about to finish it out, but the last part has absolutely stumped me. Never have I been stuck like this. It has to do with threading in Java. The Driver class reads a file, the first line indicates the number of threads, second lin...
I'm implementing a sliding window over a stream of events, in Java. So I want a data structure which allows me to do the following: add to the end of the data structure when new events occur; remove from the start of the data structure when old events are processed; get standard random access (size(), get(i)) to the elements of the data structure; in general, typical List "read" operations; i...
I was browsing through the Java docs to look for the Java equivalent for C++'s STL Queue, but all I found was an interface called Queue and a bunch of implementations I can't make heads or tails of. Does Java have an implementation for Queue that's just a FIFO data structure without the added bells and whistles? I only need the enqueue, dequeue and front operations and the data structure shoul...
Using Java (1.6) is it better to call the clear() method on a List or just re-instantiate the reference? I have an ArrayList that is filled with an unknown number of Objects and periodically "flushed" - where the Objects are processed and the List is cleared. Once flushed the List is filled up again. The flush happens at a random time. The number within the List can potentially be small (10s o...
I'd like to create some sort of Producer/Consumer threading app. But I'm not sure what the best way to implement a queue between the two. So I've some up with two ideas (both of which could be entirely wrong). I would like to know which would be better and if they both suck then what would be the best way to implement the queue. It's mainly my implementation of the queue in these examples that ...
I am helping my son with a college programming class, and I guess I need the class too. He has completed the assignment, but I don't believe he is doing it the best way. Unfortunately I can't get it to work with my better way. It's clearly better, because it doesn't work yet. He is being asked to implement some methods for a class that extends another class. He was told he must use the fo...
I only see a Queue interface, is there no Queue class in the Java Collections?
When I try: Queue<Integer> Q = new Queue<Integer>(); the compiler is giving me an error. Any help? Also, if I want to initialize a queue do I have to implement the methods of the queue?
I'm looking for a class from the Java Collection Framework that would not allow null elements. Do you know one ?
I have an immutable Iterable<X> with a large number of elements. (it happens to be a List<> but never mind that.) What I would like to do is start a few parallel / asynchronous tasks to iterate over the Iterable<> with the same iterator, and I'm wondering what interface I should use. Here's a sample implementation with the to-be-determined interface QuasiIteratorInterface: ...
I have a class that dispatches a Success and a Failure event and I need to maintain a statistic on the average number of failure/total number of events in the last X seconds from that class. I was thinking something along the lines of using a circular linked list and append a success or failure node for each event. Then count the numbers of failure nodes vs. total nodes in the list, but this ...
So I have this really large method I wrote. If it's given a stack, it will return a stack. If it's given a queue, it will return a queue. It uses a lot of recursion, and it accepts a queue/stack and returns that same queue/stack modified accordingly. I don't want to copy/paste my method just so I can change the type used inside, so is there any way I can make this generic? As in, it will accep...
HI I got this coursework question to solve. This is the question: Design a program to simulate vehicles at an intersection. Assume that there is one lane going in each of four directions, with stoplights facing each direction. Vary the arrival time of vehicles randomly in each direction and set up a regular frequency of the light changes. Run your direction and set up a regular frequency of...
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
   *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 /*
  * This file is available under and governed by the GNU General Public
  * License version 2 only, as published by the Free Software Foundation.
  * However, the following notice accompanied the original version of this
  * file:
  *
  * Written by Doug Lea with assistance from members of JCP JSR-166
  * Expert Group and released to the public domain, as explained at
  * http://creativecommons.org/licenses/publicdomain
  */
 
 package java.util;

A collection designed for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations. Each of these methods exists in two forms: one throws an exception if the operation fails, the other returns a special value (either null or false, depending on the operation). The latter form of the insert operation is designed specifically for use with capacity-restricted Queue implementations; in most implementations, insert operations cannot fail.

Throws exceptionReturns special value
Insertadd(e)offer(e)
Removeremove()poll()
Examineelement()peek()

Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator, or the elements' natural ordering, and LIFO queues (or stacks) which order the elements LIFO (last-in-first-out). Whatever the ordering used, the head of the queue is that element which would be removed by a call to or poll(). In a FIFO queue, all new elements are inserted at the tail of the queue. Other kinds of queues may use different placement rules. Every Queue implementation must specify its ordering properties.

The offer method inserts an element if possible, otherwise returning false. This differs from the Collection.add(java.lang.Object) method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues.

The remove() and poll() methods remove and return the head of the queue. Exactly which element is removed from the queue is a function of the queue's ordering policy, which differs from implementation to implementation. The remove() and poll() methods differ only in their behavior when the queue is empty: the remove() method throws an exception, while the poll() method returns null.

The element() and peek() methods return, but do not remove, the head of the queue.

The Queue interface does not define the blocking queue methods, which are common in concurrent programming. These methods, which wait for elements to appear or for space to become available, are defined in the java.util.concurrent.BlockingQueue interface, which extends this interface.

Queue implementations generally do not allow insertion of null elements, although some implementations, such as LinkedList, do not prohibit insertion of null. Even in the implementations that permit it, null should not be inserted into a Queue, as null is also used as a special return value by the poll method to indicate that the queue contains no elements.

Queue implementations generally do not define element-based versions of methods equals and hashCode but instead inherit the identity based versions from class Object, because element-based equality is not always well-defined for queues with the same elements but different ordering properties.

This interface is a member of the Java Collections Framework.

public interface Queue<E> extends Collection<E> {
    
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.

Parameters:
e the element to add
Returns:
true (as specified by Collection.add(java.lang.Object))
Throws:
java.lang.IllegalStateException if the element cannot be added at this time due to capacity restrictions
java.lang.ClassCastException if the class of the specified element prevents it from being added to this queue
java.lang.NullPointerException if the specified element is null and this queue does not permit null elements
java.lang.IllegalArgumentException if some property of this element prevents it from being added to this queue
    boolean add(E e);

    
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. When using a capacity-restricted queue, this method is generally preferable to add(java.lang.Object), which can fail to insert an element only by throwing an exception.

Parameters:
e the element to add
Returns:
true if the element was added to this queue, else false
Throws:
java.lang.ClassCastException if the class of the specified element prevents it from being added to this queue
java.lang.NullPointerException if the specified element is null and this queue does not permit null elements
java.lang.IllegalArgumentException if some property of this element prevents it from being added to this queue
    boolean offer(E e);

    
Retrieves and removes the head of this queue. This method differs from poll only in that it throws an exception if this queue is empty.

Returns:
the head of this queue
Throws:
NoSuchElementException if this queue is empty
    E remove();

    
Retrieves and removes the head of this queue, or returns null if this queue is empty.

Returns:
the head of this queue, or null if this queue is empty
    E poll();

    
Retrieves, but does not remove, the head of this queue. This method differs from peek only in that it throws an exception if this queue is empty.

Returns:
the head of this queue
Throws:
NoSuchElementException if this queue is empty
    E element();

    
Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

Returns:
the head of this queue, or null if this queue is empty
    E peek();
New to GrepCode? Check out our FAQ X