TreeSet/TreeMap problem

Hi everyone!
I'm trying to implement a Scheduler which insert some Deadline in a TreeSet (sorted by expiration timestamp): another Thread "read" TreeSet in order to remove Deadline expired. For this purpose my Deadline class implements Comparable interface and the its method compareTo in this way:
        public int compareTo (Object obj) {
            Deadline d = (Deadline) obj;
            if (this.deadline > d.deadline)
                return 1;
            else if (d.deadline > this.deadline)
                return -1;
            else {
                if (this.equals(obj))
                    return 0;
                else
                    return 1;
        }My class Deadline doesn't extends any other class and doesn't re-implements method equals.
Belove part of my "killer" thread which "read" TreeSet:
               while (v.size() > 0) {
                    dl = (Deadline) v.first();
                    if (dl.deadline <= last) {
                         v.remove(dl);
          ans = dl.deadline;
                                else {
                                    ans = dl.deadline;
                                    break;
.........In some cases (probably when timestamp deadline of Deadline class is equal to that of another Deadlne) removal of Deadline is not performed: TreeSet method first() give me a Deadline, but then I can't remove it from TreeSet. So TreeSet size is never decremented and I hava an infinite while cicle. Probably the problem is my implementation of method compareTo but I can't understand what is wrong!
Can somenone help me?
Thank you all in advance!
Diego

I want to insert in my TreeSet Deadline with the same timestamp deadline, because this can happen. When timestamp is equal, get/remove method of TreeMap should navigate in its internal tree and search, between all Deadline with the same timestamp, that which satisfy equals check.

Similar Messages

  • TreeSet, TreeMap or Comparable?

    I'm simply tackling this problem concerning a list of employee's and their division # within a company...
    Misino, John          8
    Nguyen, Viet                          14
    Punchenko, Eric          6
    Dunn, Michael          6
    Deusenbery, Amanda          14
    Taoubina, Xenia          6They're suppose to be stored in alphabetical order...My thing is, should this be approached using TreeSet, TreeMap or Comparable...From what I understand each one is, both TreeSet and TreeMap are both red/black tree implemenations of a binary search tree and TreeSet stores data with an element and a TreeMap a seperate key is created and stored in the collection while the data is stored somewhere else...Comparable seems to be used by either method considering that they are sorted and put into order in either case...Inputs anyone? I believe the information above is true, but they seem very similiar in characteristic, to me at least...

    If you're going to put it into a TreeSet or TreeMap,
    either it needs to implement Comparable, or you need
    to provide a Comparator.
    Implement Comparable if there's a sensible "natural"
    way to sort it--e.g. by last name then first, or by
    employee ID. Provide a Comparator if you want to sort
    by some arbitrary criteria that aren't necessarily a
    "natural" way to sort this class--e.g. years of
    service.
    Whether you use the Set or the Map depends on how you
    will access the elements. Will you just iterate over
    them sequentially (Set) or will you need to access
    them at random by some key (Map)?This list will be sorted by last name only...And yeah, I suppose a lot of the factor using either Set or Map depends on the accessing of elements - In general though, I think that TreeMap would be sufficient because doesn't it provides guaranteed log(n) time cost for the containsKey, find/get, insert and remove/delete operations...

  • TreeSet Comparator problem

    I've been working on a pathfinding algorithm and have been using a TreeSet with a custom comparator, but seem to have run into a problem. I'm under the assumption that a set should only contain one of each item based on the comparator. For some reason, when I do certain test cases the TreeSet will contain duplicate values. I specify that the values are equal if x == x and y == y, but somehow multiple x,y pairs are contained in the set. I use TreeSet.conatins() to determine if I should put the item in the list, but for some reason even if they share the same x,y pair it puts the same item in the list. Also, on other test cases its having trouble putting the items in the correct order. A pair of coordinates with a higher F value is in the front of the list when it should be in the back. If anyone has some suggestions i would greatly appreciate it. This is my code for the comparator. Maybe I'm doing something wrong and fresh set of eyes could help. This is my first time working with them and I'm not sure if I've made a tiny mistake or not.
    This is the custom comparator class I've implemented
        private class AStarNodeComparator implements Comparator<AStarNode>{
            public int compare(AStarNode o1, AStarNode o2) {
                return (o1.compareTo(o2));
        }And this is the compareTo, equals and hashCode method I've used for my AStarNode
        @Override
        public boolean equals(Object o){
            return(o instanceof AStarNode && this.compareTo((AStarNode)o) == 0);
        @Override
        public int hashCode() {
            int hash = 3;
            hash = 83 * hash + this.x;
            hash = 83 * hash + this.y;
            return hash;
        public int compareTo(AStarNode t) {
            if(this.x == t.getX() && this.y == t.getY()){
                return 0;
            else if(this.f < t.getF()){
                return -1;
            else{
                return 1;
        }If anyone has an idea on why this isn't sorting corectly and why it has duplicate items I would appreciate it.

    Would that exclude a value from the tree if the x and y didnt equal but the f values did? Say 1,3 = 110 and 1,2 = 110. Would it exclude one of the coordinates with that final return 0 at the end?No. It's the most minor key. It sorts items with equal (x,y) pairs only.
    I'm trying to keep duplicate x,y pairs out and sort them by f values at the same time.That is a contradiction in terms. If they are out how can you sort them? You have a major conceptual confusion here.
    Hmm would their be a different data structure I could use that would efficiently let me store them using the x,y coordinates as positions and then find the smallest one?It's not a question of which data structure, it's a question of how you are defining your ordering.
    I think your comparator should look like this:
    // Major key is 'x'
    if (this.x > that.x)
      return 1;
    if (this.x < that.x)
      return -1;
    // Sub-major key is 'y'
    if (this.y > that.y)
      return 1;
    if (this.y < that.y)
      return -1;
    // minor key is 'f'
    if (this.f > that.f)
      return 1;
    if (this.f < that.f)
      return -1;
    // Everything is equal
    return 0;As you are using a TreeSet you can throw away your hashCode() method. Otherwise it should take the 'f' value into account too.

  • Nested collections - Esp., TreeMap problem

    I am a little frustrated. Please take a look at this.
    I have a class for comparison. This is pretty simple; just do the opposite of natural TreeMap for Integer and Double.
    ============================
    package parseagain;
    import java.util.Comparator;
    public class ReverseComparator<T> implements Comparator<T> {
         public int compare(T o1, T o2) {
              if (o1 instanceof Integer) {
                   if ((Integer)o1 < (Integer)o2) return 1;
                   else if ((Integer)o1 == (Integer)o2) return 0;
                   else return -1;
              else if (o1 instanceof Double) {
                   if ((Double)o1 < (Double)o2) return 1;
                   else if ((Double)o1 == (Double)o2) return 0;
                   else return -1;
              else {
                   throw new ClassCastException();
    ==============================
    Then, I have a long program, part of which is shown below. What it does is that put pixel information into a HashMap of TreeMap, then retrieve them. you know what? this prints 'NULL' like shown below it.
    ==============================
              HashMap<Integer, TreeMap<Integer, Integer>> colorXY = new HashMap<Integer, TreeMap<Integer, Integer>>();
              if (direction == 1) {
                   for (Integer iColor : colorsDrawing) {
                        System.out.printf("iColor is %d\n", iColor);
                        colorXY.put(iColor, new TreeMap<Integer, Integer>(new ReverseComparator<Integer>()));
              else {
                   for (Integer iColor : colorsDrawing)
                        colorXY.put(iColor, new TreeMap<Integer, Integer>());
              HashSet<Integer> temp = new HashSet<Integer>();
              for (int xi = left + 1; xi < right; xi++) {
                   colorsMet.clear();
                   for (int yi = top + 1; yi < bottom; yi++) {
                        int color = colors[yi][xi];
                        if (yi > posZero) {
                             color = (color * -1) - 1;
                             //System.out.printf("in color is %d\n", color);
                        // if this color is not what I want, skip.
                        if (colorsDrawing.contains(color) == false) continue;
                        if (color >= 0) {
                             // if upward, check if I already have it.
                             if (colorsMet.contains(color) == true) continue;
                             colorsMet.add(color);
                        colorXY.get(color).put(xi, yi);
                        if (xi == 694) {
                             temp.add(color);
                             System.out.printf("color: %d xi: %d yi: %d\n", color, xi, yi);
                   if (xi == 694){
                        for (Integer iColor : temp)
                        System.out.println("temp " + colorXY.get(iColor).get(xi) + " " + iColor);
    ==============================
    Here is the output:
    ==============================
    iColor is -8913033
    iColor is 16119285
    iColor is 8913032
    iColor is 16711680
    iColor is 65280
    iColor is -137
    iColor is -34817
    iColor is 255
    iColor is -8912897
    color: 8913032 xi: 694 yi: 139
    color: 255 xi: 694 yi: 142
    color: 65280 xi: 694 yi: 176
    color: 16711680 xi: 694 yi: 207
    color: 16119285 xi: 694 yi: 212
    color: -8912897 xi: 694 yi: 213
    color: -8912897 xi: 694 yi: 214
    color: -8912897 xi: 694 yi: 215
    color: -8912897 xi: 694 yi: 216
    color: -137 xi: 694 yi: 217
    color: -137 xi: 694 yi: 218
    color: -137 xi: 694 yi: 219
    color: -137 xi: 694 yi: 220
    color: -137 xi: 694 yi: 221
    color: -34817 xi: 694 yi: 222
    color: -137 xi: 694 yi: 223
    color: -137 xi: 694 yi: 224
    color: -137 xi: 694 yi: 225
    color: -137 xi: 694 yi: 226
    color: -137 xi: 694 yi: 227
    color: -137 xi: 694 yi: 228
    color: -137 xi: 694 yi: 229
    color: -8913033 xi: 694 yi: 230
    color: -8913033 xi: 694 yi: 231
    temp null -8913033
    temp null 16119285
    temp null 8913032
    temp null 16711680
    temp null 65280
    temp null -137
    temp null -34817
    temp null 255
    temp null -8912897
    ==============================
    It can't happen! I already put (several times)! Can anyone tell me why?

    Thanks. It worked fine.
    I also thank you for the comments on "the next
    thread." I will not do that again.
    I don't use forum before, so just understand me.No problem. Glad my suggestion worked for you.

  • How to get TreeSet from TreeMap?

    Hi,
    I tried the following:
    (TreeSet)treeMap.keySet()Is there a way to get the treeset from treemap without creating a new instance of treeset and adding all values from this keySet?

    leden wrote:
    Hi,
    I tried the following:
    (TreeSet)treeMap.keySet()Is there a way to get the treeset from treemap without creating a new instance of treeset and adding all values from this keySet?No, as is quite clear from the docs. TreeMap's keySet() method is only guaranteed to return some Set implementation. If you want a specific implementation, you have to create it. Is that a problem, and if so, why?

  • Class structure proposal

    hi,
    I've dillema with organizing my classes in my program. The program should
    manage materials and their bill of materials (bom). So I've created one
    class "Materials" which hold id of the material and ... yes it's bom.
    The dillema is should bom object holds both parent code and child code?
    How would you solve my problem. The snippet of my code is bellow:
    class Material{
    int materialid;
    BOM bom;
    class BOM{
    Material parentmaterial; //schould I remove it since it's bound to
    //the Material
    Collection bomitems //collection of BOM Items since material can have
    //more component than one
    class BOMItem{
    Material childmaterial;
    int quantity;

    As per my understanding goes, in a Bills of Material (BOM) scenario,
    - An item is made up of sub-items and this hierarchy could go upto any limits.
    Essentially from data angle    Parent Item    Child Item
        Item 1         Item 2
        Item 2         Item 3
        Item 2         Item 4
        Item 2         Item 5
        Item 4         Item 6
        Item 6         Item 7
        Item 7         Item 8
        Item 9         Item 10java representationpublic class item() {
        //attributes of item e.g. ArrayList/HashSet/HashMap children;
        //methods of item e.g. getParent()
    }You could also use java collection objects like TreeSet/TreeMap to implement your BOM.
    Things get a little bit complicated if a sub-item might have multiple parents (say, Item i, could be made of a combination of Item j & Item k, or, a combination of Item m, Item n and Item o
    Hope it helps,

  • Can someone explan to me

    this method is part of my lab, it should sort words in alphabetical order from
    from A to Z . .
    i don;t undersatand why did we use .compareTo in this method??
    could someone explain what does this method mean
    public static void sortList()
              String temp;          
              for(int k = 0; k < count-1; k++)
             for(int p = k+1; p < count; p++)
              if(list[k].compareTo(list[p]) > 0)
                        temp = list[k];
                        list[k] = list[p];
                        list[p] = temp;
    }

    If all of the elements in a collection implement the Comparable interface, which defines the compareTo method, then the sorting can be done automatically using a TreeSet( ), TreeMap( ), or Collections.sort( ) method. For example:
    public class MyClass
    implements Comparable
       public int compareTo( Object o )
          if( equals( o ) ) return 0;
          if( o == null ) return -1;
          if( !(o instanceof MyClass) ) throw new ClassCastException( );
          MyClass that = (MyClass)o;
          if( this.getValue( ).lessThan( that.getValue( ) )
              return -1;
          else
              return 1;
    public class SomeOtherClass
        public void someMethod( )
            List myClassList = new ArrayList( );
            for( int i = 0; i < 10; i++ ) myClassList.add( new MyClass( ) );
            // Sorts myClassList by casting each element to Comparable
            // and calling compareTo( )
            List sortedList = Collections.sort( myClassList );
    }

  • Find best collection class for the scenarios given

    Hi Everyone,
    Can u help me in answering this questions:
    Indicate the most efficient / appropriate standard Java (JDK 1.4 or lower) collections class for each requirement. Do not use any classes that are not in the standard JDK (e.g. Apache commons-collections classes).
    2.1. An un-ordered, unique collection
    2.2. An insertion-ordered, non-unique collection
    2.3. A sorted, unique collection
    2.4. An insertion-ordered, unique collection
    2.5. Random access to elements within a list
    2.6. Insertion into random points within a list
    2.7. A last-in-first-out queue
    Please let me know what u think ?
    IF possible please tell me the reason why u selected one over the other
    Thanks in advance....

    2.1. An un-ordered, unique collection
    HashSet thereadOkay, why?
    2.2. An insertion-ordered, non-unique collection
    LinkedList thereadOkay, why?
    2.3. A sorted, unique collection
    TreeSet theread
    TreeMap kv pair thereadOkay, but is collection with a small "c" or Collection with a captial "C"? Maps don't implement the Collection interface. In a general sense, you could consider them collections, but in Java land, usually that implies single-valued groupings--i.e., those that implement Collection.
    >
    2.4. An insertion-ordered, unique collection
    LinkedHashSet theread
    LinkedHashMap thereadSame comments as above.
    2.5. Random access to elements within a list
    LinkedList (In fact any class that implements List
    Interface)No. Hint: Do you know what "random access" means, and why LinkedList is not a good choice?
    2.6. Insertion into random points within a list
    LinkedHashSet
    LinkedHashMapNo. It doesn't say anything about uniqueness or k/v pairs.
    2.7. A last-in-first-out queue
    StackOkay.
    2.8. List any of these classes which are not
    thread-safe, if any. How
    would you make these Collections thread-safe?
    HashSet, LinkedList, TreeSet, TreeMap, LinkedHashSet,
    LinkedHashMapI'm not going to match 'em all up one by one, but it seems about right.
    This is typically accomplished by synchronizing on
    some object that naturally encapsulates the collection
    class. If no such object exists, the map should be
    "wrapped" using the Collections.synchronizedMap
    method. This is best done at creation time, to prevent
    accidental unsynchronized access to the map:
    Map m = Collections.synchronizedMap(new TreeMap(...));Sounds about right. Also sounds like it was copied and pasted. If so, do you understand it?

  • Problem with TreeSet and tailset

    I have a TreeSet with a large number of objects (7000+). I am using tailset to get the specific objects I want from the TreeSet. This is usually only the last few objects. Then, I write this returned set to an ObjectOutputStream using the writeObject method. The problem is that it takes a long time for the writeObject method to complete. If my original TreeSet only has around 1000 objects in it, then the writeObject method completes rather quickly. It seems as though the TreeSet returned by the tailSet method is much larger than I think it is. Even if tailSet returns a TreeSet with no objects in it, the writeObject still takes the same (long) amount of time to complete.
    Is there something I do not understand about the TreeSet returned by the tailSet method?
    Thanks,
    Jeff Lueders
    [email protected]

    tailSet() just creates an view from the original Set. In the case of TreeSet, which is implemented via TreeMap, not much happens when you create this view. Only a tiny Object is created, of type private class TreeMap.SubMap, which holds information of the first element of this view and that it is supposed to extend all the way to the end. So every access to the tail set still needs to go through your huge original Set.
    One way to reduce this lookup overhead to a single-time operation would be to copy the tail set into a new TreeSet, which is definitely truly smaller but will not be directly backed by the original Set anymore. So concurrent changes inside any of the Sets will not effect the other.
    Set  tailSet = new TreeSet(originalSet.tailSet(startKey));

  • Problem using TreeSet sorting

    Hello to everyone. I am starting to learn java and I hope that you guys can help me with my problem. I am using a TreeSet right now and is adding to the set one by one by using the add method. My problem is that everytime I inserted to the Set, it doesnt follow my adding order! Its weird because I am using a comparator class to sort this out properly but still it doesnt work, here is my code:
    Declaration of TreeSet object:
    private OptionsComparator optionsComparator = new OptionsComparator();
    private Set<Options> optionSet;
    optionSet = new TreeSet(optionsComparator);
    my OptionsComparator Class:
    public class OptionsComparator implements Comparator<Options> {
    public int compare(Options opt1, Options opt2) {
    int x = opt1.compareTo(opt2);
    if (x != 0)
    return x;
    return (opt1.getOptOrder() < opt2.getOptOrder() ? -1 :
    (opt1.getOptOrder() == opt2.getOptOrder() ? 0 : 1));
    public boolean equals(Object collator) {
    if (this == collator) {             // If argument is the same object
    return true; // then it must be equal
    if (collator == null) {             // If argument is null
    return false; // then it can�t be equal
    return getClass() == collator.getClass(); // Class must be the same for equal
    This is how I added the records:
    optionSet.add(1);
    up to 10
    So after I tried to enter some records, it looks like this:
    2
    4
    9
    8
    6
    1
    3
    10
    7
    5
    Am I doing something wrong? Am I using the comparator class incorrectly? Thanks in advance.

    Well, you're constructing a Set to hold Options
    objects, but what you seem to be inserting are
    Integer objects. What I don't get is why it's even
    compiling.
    If what you've shown is wrong, and what you are
    actually inserting are Options objects, then it's
    probably down to the definition of compareTo in the
    Options class.thank you for replying, sorry about that, I forgot that I was supposed to enter the values for the set, what I meant was this:
    option.setValue(1);
    so on and so fort:
    for my implementation of the compareTo in my Options class, here it is:
    public int compareTo( Options o ) {
    if ( this.optOrder < o.getOptOrder() )
    return -1;
    if ( this.optOrder == o.getOptOrder() )
    return 0;
    else
    return 1;
    so there, I also have a member in the object called optOrder which keeps track of the order for the Set, still not sure why this doesnt work though

  • Problem in using TreeSet with a Comparator

    Hello,
    There seems to be a bug in the implementation of TreeSet, while using a specific Comparator to sort its elements.
    Here's the problem I got into: the Comparator I use has a type parameter which defines, of course, the type of objects that may be compared. These objects have an integer field 'value'. In the redefinition of 'compare' method inside the Comparator, if the values are equal, 0 is returned, otherwise returns -1 or 1.
    Now, I want to add objects into my TreeSet having this Comparator. But, when I call add for an object that has the field 'value' equal to a value from an object that is already in the Tree Set, it doesn't add it. I red the API documentation, which says that a non-null object o1 is not added into the tree set if there is already an object o2 such that o1.equals(o2) returns true. Or, my objects are far from being equal: the references are different, there are even some fields different.
    Nevertheless, all my elements are comparable.
    Am I ignoring something or is there a bug?
    Thanks.

    When I call add for an object that has the field 'value' equal to a value from an object that is already in the Tree Set, it doesn't add it.Correct. That's how it is supposed to behave. A Set cannot contain duplicates.
    I read the API documentationEvidently not all of it ;-)

  • Problem with TreeMap and Vector

    Hello,
    this is the problem I have:
    I declare a Vector like this:
    Vector<String> theVector = new Vector<String>();
    I put the String needed into the Vector:
    theVector.add("blabla")
    In the other hand I had created a TreeMap like this:
    private TreeMap<Integer, Vector<String>> theTreeMap;
    I now when I try to put the Key and the Element like this my program crash:
    theTreeMap.put(1096,theVector);
    I think I don't put the data on the good way in the TreeMap...
    Any Idea? Thank you very much

    In the other hand I had created a TreeMap like this:
    private TreeMap<Integer, Vector<String>> theTreeMap;
    I now when I try to put the Key and the Element like
    this my program crash:
    theTreeMap.put(1096,theVector);What do you mean?

  • Problem with TreeMap

    I had a problem that I believe was similar to this posting:
    http://forum.java.sun.com/thread.jsp?forum=24&thread=200558
    although mine involves a TreeMap. I am adding approximately 250 mappings to a TreeMap, where the key is a String. Each key is unique, and, just to be sure, I analyzed the hashCode of each key, and they were also unique.
    After adding all of the mappings, however, the total size of the TreeMap is only 40! Somewhere, app. 210 mappings were overwritten. I added some debug code and found that after I added the 10th element, the size of the TreeMap did grow. Then the TreeMap would grow only on every 3rd mapping that I would add.
    The above-referenced posting mentioned that the rehashing of the map might cause it to overwrite existing values, so it made sense to set the initial capacity high enough to ensure that no rehashing occurred. Unfortunately, that posting dealt with a HashMap, which allows you to set the initial capacity. TreeMaps do not. In order to mimic this behavior, I added all of the mappings into a HashMap with an initial capacity of 250. When the HashMap was loaded, I created the TreeMap (with a unique Comparator), and then used the putAll() method of TreeMap to put the entire HashMap into the TreeMap. Voila! All 250 mappings were there.
    Nonetheless, this seems to be a very strange bug with TreeMap. Does anyone know why this happened?

    Sorry. Figured out the problem. It was all my fault (based on the comparator I was using, which caused the keys to be overwritten). how dare I accuse Sun of deploying buggy software. :)

  • Sorting problem in TreeMap, please help urgent :-((

    Hi
    Following is a program, please execute it to see the problem. I am adding four elements in the TreeMap. The problem is when I add the elements it never compares the newly added element with the first element. I was sick of it so to test the TreeMap I created my own small class and defined a Comparator for that class. Following is the code which shows the problem in TreeMap. Am I doing something wrong? Please help its urgent.
    import java.util.*;
    public class SortingCollection {
         public static void main(String[] args) {
              SortingCollection sortingCollection = new SortingCollection();
              sortingCollection.sortingTest();
         public void sortingTest() {
              TreeMap treeMap = new TreeMap();
              treeMap.put(new Test("Bhushan", 1022), new Integer(1022));
              treeMap.put(new Test("Wasil", 1023), new Integer(1023));
              treeMap.put(new Test("Ifti", 1020), new Integer(1020));
              treeMap.put(new Test("Roshan", 1021), new Integer(1021));
              System.out.println(treeMap);
              Test test = new Test("Bhushan", 1028);
              treeMap.put(test, new Integer(1022));
              System.out.println(treeMap);
         public class Test implements Comparable {
              public String name;
              public int age;
              public Test(String name, int age) {
                   this.name = name;
                   this.age = age;
              public int compareTo(Object toBeCompared) {
                   Test casted = (Test) toBeCompared;
                   if (name.equals(casted.name)) {
                        System.out.println("Returning 0 for " + name + " " + casted.name);
                        return 0;
                   System.out.println("Returning -1 for " + name + " " + casted.name);
                   return -1;
              public String toString() {
                   return "[" + name + ", " + age + "]";
    }

    If you are using TreeMap, you should want the keys to be immutable. You can't change the state of the keys of a Map such that their natural order will change, or chaos will happen.
    If the key is the GateKeeperInfo class (which has host, port, and # of users as its data members) and the value is "some other object reference which you need", and this reference is closely tied to the GateKeeperInfo, have you considered making it a member of the GateKeeperInfo?
    That way you don't need this TreeMap business. You can have the natural ordering imposed on the GateKeeperInfo class (which is apparently comparing the host and port only). You can also have a Comparator object that can compare these objects in a different way (# of users, for instance).
    public class MyClass implements Comparable
       String host;
       int    port;
       int    currNumUsers;
       Object someOtherObjectReferenceINeed;
       // or if the object reference you need is an Integer, make that last member
       // an int...
       // Also, let's keep a Comparator in here for comparing # of users.
       // See further down for actual implementation...
       public static final Comparator BY_NUM_USERS = new NumUsersComparator();
         // Use the equal methods to determine whether or not host and port matches
       public boolean equals( Object obj )
       // Use the compareTo method to compare 2 instances in terms of host and port
       public int compareTo( Object obj )
         // Make this object take care of changing # of users, outside of the
         // Comparable interface.
         public int getNumUsers();
         public int bumpNumUsers( int byThisAmount ); // changes # of users...
         // Beef up this object to take advantage of someOtherObjectReferenceINeed
    // Use this Comparator object to compare 2 instances of MyClass
    // according to # of users.
    public class NumUsersComparator implements Comparator
         public int compare( Object a, Object b )
              MyClass left      = (MyClass)a;
              MyClass right      = (MyClass)b;
              // I am assuming both # of users are of the same sign...positive
              return ( right.getNumUsers() - left.getNumUsers() );
    // Now when you need to compare, you can do it 2 different ways...
    // You can use whatever Collection you fits, List, Set, ...
    // I am going to use List in this case
    List gateways = new ArrayList;
    // add the objects...
    gateways.add( /* . . . */ );
    // Now let's sort in terms of user/port
    Collections.sort( gateways );
    // Let's sort in terms of number of users...
    Collections.sort( gateways, MyClass.BY_NUM_USERS );
    // I am going to mix them around now...
    Collections.shuffle( gateways );
    // Now let's find the gateway w/ the largest # of users...
    MyClass currMaxGateway = Collections.max( gateways, MyClass.BY_NUM_USERS );
    .

  • A problem with treemap

    In a file, I have 400, 000 lines of data. There are around 16000 keys. Each key can have multiple values.
    eg:
    Key - Var1 - Var2
    5 - 132.1 - 0.678
    5 - 128.5 - 0.523
    2 - 110.0 - 0.253
    6 - 20.0 - 0.245
    I sorted using TreeMap. However, only 12463 keys gets added to TreeMap. I don't know what's wrong . If someone can help me out with this problem, that would be great!!!
    -Karthik

    So if you want to use the standard HashMap you have to deal with multiple keys yourself.
    One way is to first check if the key's already in the map. If it isn't you store the key/item pair as you do now. If the key's already in the map you switch to a collection of items using a collection, for example a LinkedList. The end result is that each key is uniqueande there are two types of items; single items and collections of items.

Maybe you are looking for