User
User

Reputation: 1726

How does remove function work with min priority queues that contain string values?

I understand that if I remove an element from a min priority queue, it will remove the smallest element first. For example, if I have a min priority queue of a bunch of int values, such as 1, 2, 3, if I call the remove function, it will remove 1.

What about if I have a min priority queue of a bunch of string values? For example, if I have a priority queue with "Tom", "Moe", "Brandon", "Alexander", would it just remove the min value according to lexicographic sorting? If so, I imagine it would remove "Moe" first. Then if I called remove again, it would remove "Tom".

Is my understanding correct? The below pseudo-code details the exact code I am looking at.

public interface Container<T>
{
 void insert(T x);  // insert x into Container
  T remove();       // remove item from Container
}

public class C<T> implements Container<T>
{
 public C() { /* constructor */ } 
 public void insert(T x) { /* insert x into C */ }
 public T remove() { /* remove item from C */ }
 //.. other methods
}

Here is a program segment that uses class C above:

Container<String> words = new C<String>();
String w1 = "Tom";
String w2 = "Dick";
String w3 = "Harry";
String w4 = "Moe";
words.insert(w1);
words.insert(w2);
words.insert(w3);
words.insert(w4);
String str = words.remove(); // remove
str = words.remove();        // remove again
System.out.println(str);

Upvotes: 0

Views: 1519

Answers (1)

scadge
scadge

Reputation: 9733

The PriorityQueues usually accept a Comparator in order to determine how to sort the values inside. If you don't provide one, then Java uses the default comparison method: like 1 is less than 2 and "A" is less than "B".

So in your example, the default lexicographic order will be: Alexander, Brandon, Moe, Tom (like in alphabet). Also note than "a" is less than "A", so the case also matters.

Upvotes: 1

Related Questions