Multiple indexes for a Java Collection - most basic solution?

后端 未结 14 1756
小鲜肉
小鲜肉 2020-11-29 22:08

I\'m looking for the most basic solution to create multiple indexes on a Java Collection.

Required functionality:

  • When a Value is removed, all index en
14条回答
  •  萌比男神i
    2020-11-29 22:50

    Your main goal seems to be that you'll remove the object from all indexes when you remove it from one.

    The simplest approach will be to add another layer of indirection: you store your actual object in a Map, and use a bidirectional map (which you'll find in Jakarta Commons and probably Google Code) for your indexes as Map. When you remove an entry from a particular index, you'll take the Long value from that index and use it to remove the corresponding entries from the main map and the other indexes.

    One alternative to the BIDIMap is to define your "index" maps as Map>; however, this will require you to implement a ReferenceQueue for cleanup.


    Another alternative is to create a key object that can take an arbitrary tuple, define its equals() method to match on any element in the tuple, and use that with a TreeMap. You can't use a HashMap, because you won't be able to compute a hashcode based on just one element of the tuple.

    public class MultiKey
    implements Comparable
    {
       private Comparable[] _keys;
       private Comparable _matchKey;
       private int _matchPosition;
    
       /**
        *  This constructor is for inserting values into the map.
        */
       public MultiKey(Comparable... keys)
       {
          // yes, this is making the object dependent on externally-changable
          // data; if you're paranoid, copy the array
          _keys = keys;
       }
    
    
       /**
        *  This constructor is for map probes.
        */
       public MultiKey(Comparable key, int position)
       {
          _matchKey = key;
          _matchPosition = position;
       }
    
    
       @Override
       public boolean equals(Object obj)
       {
          // verify that obj != null and is castable to MultiKey
          if (_keys != null)
          {
             // check every element
          }
          else
          {
             // check single element
          }
       }
    
    
       public int compareTo(Object o)
       {
          // follow same pattern as equals()
       }
    }
    
        

    提交回复
    热议问题