Java cache in map versus list
Currently in my legacy code I have been caching some DB information as a list List<CachedObject>
.
CachedObject
looks something like this:
public class CachedObject
{
private int id;
private int id_type;
private int id_other_type;
// getters and setters
}
Most of the time I get one specific object via a function:
public CachedObject getById( Integer id )
{
if( id != null )
for ( CachedObject cachedObject : this.cachedObjectList )
if( cachedObject.getId().equals( id ) )
return cachedObject;
return null;
}
My question: would it be better to cache the object in Map<Integer, CachedObject>
using id
as a key. My problem in this scenario is that my other recipients from this list should look like this:
public CachedObject getByIdType( Integer id )
{
if( id != null )
for ( CachedObject cachedObject : cachedObjectList.values() )
if( cachedObject.getId().equals( id ) )
return cachedObject;
return null;
}
I haven't done this before because I really don't know the downsides of this map cache and it seems like it's silly not to.
source to share
Good HashMap.values()
returns a collection. There is no computation or data copying. It's as fast as it can get.
Thus, caching in the form of a HashMap is the thing to do in your case.
But consider that if in any case you want List<CachedObject>
in your code
ArrayList<CachedObject> list = new ArrayList<CachedObject>(hashMap.values());
ArrayList, valuesList calls the collection's hashMap method toArray()
, which essentially makes a for loop out of the 0..N (size) item in the collection.
source to share
If you are using a map, you don't need a loop. Your code can be reduced to:
public CachedObject getByIdType( Integer id )
{
if( id != null )
return cachedObjectList.get(id);
else
return null;
}
This is much more efficient than repeating all the items in the list (or all the values โโin the map).
source to share