0

I need your help. If i want to sort a PriorityQeueu in java, with out connection to it's attributes - could i use the hashCode's Objects to compare?

This how i did it:

comp = new Comparator<Person>() {

        @Override
        public int compare(Person p1, Person p2) {
            if(p1.hashCode() < p2.hashCode()) return 1;
            if(p1.hashCode() == p2.hashCode()) return 0;
            return -1;
        }
    };
collector = new PriorityQueue<Person>(comp);
Mohsen_Fatemi
  • 2,183
  • 2
  • 16
  • 25
Yos
  • 41
  • 1
  • 6

1 Answers1

0

It doesn't sound like a good approach. Default hashCode() is typically implemented by converting the internal address of the object into an integer. So the order of objects will differ between application executions. Also, 2 objects with the same set of attribute values will not return the same hashCode value unless you override the implementation. This actually breaks the expected contract of Comparable.

bbb8989
  • 13
  • 4
  • So, you have something else to suggest? – Yos Jan 29 '17 at 08:58
  • http://stackoverflow.com/questions/9704554/sorting-arraylist-of-objects-using-hashcode Unless you implement correct Comparator - you PriorityQueue is as good as unsorted collection. Just to make it clear. With hashCode you will get consistent order within one application instance (JVM). It is simply not correct approach. – bbb8989 Jan 29 '17 at 11:57