简体   繁体   中英

TreeMap in Java

import java.util.Comparator;
import java.util.TreeMap;
public class Manager {

     public static void main(String[] args) {

          TreeMap tmap1 = new TreeMap(new C.D());
          tmap1.put(new C(9, 1), 9);
          tmap1.put(new C(0, 10), 19);
          tmap1.put(new C(1, 8), 92);
          tmap1.put(new C(8, 0), 91);
          tmap1.put(new C(5, 4), 39);
          tmap1.put(new C(5,4), 73);//this line

          System.out.println(tmap1);
        }
}

  class C {
      int i, j;

         C(int i, int j) {
             this.i = i;
             this.j = j;
           }

        public String toString() {
           return "(i=" + i + ",j=" + j + ")";
         }

       static class D implements Comparator {
             public int compare(Object obj1, Object obj2) {
               return ((C)obj1).i - ((C)obj2).i;
             }
      }

  }

//As we know TreeMap sorts based on the key and here I am passing it a comparator and its sorting based on variable i.When I tried to enter new entry in treemap1 as I mentioned it in comment as //this line , its adding this new entry while deleting previous same entry. Well Class C does not override hashcode() and equals() method so the new entry is completedly different from it previous entry as they have different hashcode() based on Object class, so both entries should retain in map but only new one is added and previous one deleted.

In case of line

tmap1.put(new C(5,4), 73);

your comparator returns 0 so it is duplicate for JVM and it overrides it.

Put one debug statement like below and re-run your program you will understand the fact..

     public int compare(Object obj1, Object obj2) {
       System.out.println("in compare difference is : "+ (((C)obj1).i - ((C)obj2).i));
       return ((C)obj1).i - ((C)obj2).i;
     }

you will get below output..see the zero(0) at last

in compare : -9
in compare : -8
in compare : 1
in compare : 7
in compare : -1
in compare : 4
in compare : -4
in compare : -3
in compare : 4
in compare : -3
in compare : 0

In your case the problem is because if you use TreeMap and provide Comparator you should also provide correct equals method. It's in JavaDoc of TreeMap:

Note that the ordering maintained by a tree map, like any sorted map, and whether or not an explicit comparator is provided, must be consistent with equals if this sorted map is to correctly implement the Map interface

Your equals method is inherited from Object and it's not consistent with your Comparator.

Have a loot at TreeMap put method and compare it with HashMap put method. TreeMap's version use compareTo method only instead of equals like in HashMap's put.

Btw you shouldn't use raw types since Java 1.5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM