Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java cache in map vs list

Tags:

java

caching

Currently in my legacy code i have cached some DB info in form of 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 am fetching one specific object via 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 is would it be better to cache object in Map<Integer, CachedObject>with id as key. My concern in that scenario is that my other getters from that list have to look like:

    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 drawbacks of this map cache, and it seems silly not to do this in the first place.

like image 262
Ivan Pavić Avatar asked Jul 14 '26 00:07

Ivan Pavić


1 Answers

Well HashMap.values() directly returns a Collection. There is no computation or data copying done. It's as fast as it can be.

So caching in form of 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());

the ArrayList, valuesList calls the collection hashMap toArray() method which essentially does a for loop from 0..N (size) element in the collection.

like image 78
John Avatar answered Jul 15 '26 14:07

John



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!