daily pastebin goal
22%
SHARE
TWEET

Untitled

a guest Aug 10th, 2018 50 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. PriorityQueue returning incorrect ordering for custom comparator?
  2. public class PriQueTest {
  3.   public static void main(String[] args) throws IOException {
  4.     // TODO Auto-generated method stub
  5.     Comparator<String> comparator = new StringPriComparator();
  6.     PriorityQueue<String> queue =
  7.         new PriorityQueue<String>(3, comparator);
  8.     queue.add("3"+"128763711");
  9.     queue.add("2"+"128763712");
  10.     queue.add("0"+"128763718");
  11.     queue.add("1"+"128763713");
  12.     queue.add("3"+"128763714");
  13.     queue.add("2"+"128763715");
  14.     queue.add("2"+"128763716");
  15.     queue.add("3"+"128763717");
  16.  
  17.     while (queue.size() != 0)
  18.     {
  19.         System.out.println( (queue.remove().substring(1)));
  20.     }
  21.  
  22.   }
  23.   public static class StringPriComparator implements Comparator<String>
  24.   {
  25.     @Override
  26.     public int compare(String x, String y)
  27.     {
  28.         if (Integer.parseInt(x.substring(0, 1)) >  Integer.parseInt(y.substring(0, 1)))
  29.         {
  30.             return -1;
  31.         }
  32.         if (Integer.parseInt(x.substring(0, 1)) <  Integer.parseInt(y.substring(0, 1)))
  33.         {
  34.             return 1;
  35.         }
  36.         return 0;
  37.  
  38.      }
  39.   }
  40.  
  41.  
  42. }
  43.    
  44. 128763711
  45. 128763714
  46. 128763717
  47. 128763716
  48. 128763712
  49. 128763715
  50. 128763713
  51. 128763718
  52.    
  53. 128763711
  54. 128763714
  55. 128763717
  56. 128763712*
  57. 128763715*
  58. 128763716*
  59. 128763713
  60. 128763718
  61.    
  62. public static class StringPriComparator implements Comparator<String> {
  63.     @Override
  64.     public int compare(String x, String y) {
  65.         if (Integer.parseInt(x.substring(0, 1)) > Integer.parseInt(y.substring(0, 1))) {
  66.             return -1;
  67.         }
  68.         if (Integer.parseInt(x.substring(0, 1)) < Integer.parseInt(y.substring(0, 1))) {
  69.             return 1;
  70.         }
  71.         return x.substring(1).compareTo(y.substring(1));
  72.     }
  73. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top