0

I am not sure if my title truly reflects what I want to ask. I have a Java class called Light with a field: private int state. I am looking for suggestions on what would be a better / fastest way to access the "state" field as all the Light objects will be stored in a HashMap. (HashMap's key is int id.) and Light.state gets updated frequently. An example of my operation is: get me all Light objects that are in state = 2. after I get everything in state=2, I might need to change a few to state = 3. I thought of bitmap, but I don't store state in the database only in the cache for faster access/modification. I am not sure how to implement bitmap on a field in an object. I am all ears on any possible solutions. Thanks in advance!

class Light {
   private int state = 0;
   ....other fields....
   public void setState(int state) {
       this.state = state;
   }
}

HashMap<Integer, Light> cache ; // Integer is id not state
asun
  • 151
  • 5
  • 15
  • You must manually maintain a separate index for all you want to know. A map from Integer to a Set of Light might be a good starting point. Every time a state field is updated, you must update your index structures. – Thorbjørn Ravn Andersen Jun 30 '17 at 04:11
  • Don't worry about micro-optimizations. Focus on writing understandable code. If this select is performance-critical, you'll need some sort of index anyway. – chrylis -cautiouslyoptimistic- Jun 30 '17 at 04:15
  • 1
    pre-optimization is the root of all evil (or something) – Scary Wombat Jun 30 '17 at 04:17
  • is there a way to avoid having another map to store the field? – asun Jun 30 '17 at 04:23
  • you don't need another map..chnage your cache to something like this.. `HashMap> cache;` as far as I understood there can have multiple `Light` for a given state; – Jobin Jun 30 '17 at 04:30
  • My bad. I didn't state my question clearly. HashMap, the Integer is for id not state. Id is the most frequent accessed key, then it's state. is there a way to utilize the existing cache to provide such search ? – asun Jun 30 '17 at 04:48
  • 1
    You might be able to get some ideas from [here](https://stackoverflow.com/questions/44801274/in-populating-an-observablelist-do-i-have-to-load-all-the-records-from-my-datab/44802369#44802369). Look at the "Filtering a table in Java (all objects in memory)" part. – SedJ601 Jun 30 '17 at 05:00
  • @SedrickJefferson thanks! – asun Jun 30 '17 at 06:53

0 Answers0