質問

Was wondering if there was a way to use a priority Queue to take an Array with random numbers in it and then delete them based on something like Biggest to smallest or smallest to biggest. Or if it has the number 3 in it.

You would use a comparator for that right?

役に立ちましたか?

解決

How you can do this with standard Java libraries:

    Integer[] ints = new Integer[]{3,2,1};

    // For reverse of natural order i.e. largest to smallest
    // If you want the natural order don't use the Collections.reverseOrder() comparator
    Queue<Integer> queue = new PriorityQueue<Integer>(ints.length, Collections.reverseOrder());
    queue.addAll(Arrays.asList(ints));

    while (queue.size() > 0) {
        System.out.println(queue.poll());
    }

他のヒント

To add to xlm's answer, after you create a priority queue from the random array and want to delete a certain element, e.g., 3 from it, you can simply call the remove() method in PriorityQueue class

queue.remove(3);

This doesn't necessarily remove the element from the queue head like what poll() does if 3 is not the maximum number in the queue.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top