0

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?

Durandal
  • 5,575
  • 5
  • 35
  • 49
user3307265
  • 35
  • 2
  • 7

2 Answers2

0

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());
    }
xlm
  • 6,854
  • 14
  • 53
  • 55
  • So what if you want to compare an object, Let's say there is an array of Rectangles and they all have different lengths and widths how would you compare the width of the rectangles? Could you then delete let's say the rectangle with the biggest width first? Assuming you don't already know which ones are the biggest generated randomly. – user3307265 Feb 13 '14 at 22:06
  • 1
    You would write a `Comparator` for your class that compares them as you need. See http://stackoverflow.com/questions/683041/java-how-do-i-use-a-priorityqueue – xlm Feb 13 '14 at 22:09
  • Would I do something like Comparator comparator= new Comparator(); for the Comparator?And then I would then make a comparator class that would do what I needed it to do? – user3307265 Feb 13 '14 at 22:29
  • @user3307265 That's right. You can create a named `Comparator` or an anonymous one. You then implement the `compare` method to return the desired ordering. Let me know if you need more help, if not please mark as correct. – xlm Feb 14 '14 at 00:28
0

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.

tonga
  • 11,749
  • 25
  • 75
  • 96