I have a data structure, like this:
public class Data{
private String charData;
private int intData;
//get-set methods here
}
Now, I want to create a lru cache and I need to override sizeof…as each char in java occupies 2bytes, while an int is 4 bytes I though making:
cachedData= new LruCache<String,Data>(CACHE_MB*1024*1024){
protected int sizeOf(String k,Data v){
return 4 +2*v.getCharData().length();
}
but Strings are objects, so I think they take more than just memory for characters, moreover Data is an object too so I’m not sure my method is correct.
By the way what happens if I reach maximum cache size with a wrong sizeOf method?
I think you did not understand the use of the
sizeOf()method:This method can be overridden in specific cases where the size of certain entries store in the cache are significantly larger than others (this can happen when caching Bitmaps). In this way, you can specify the maximum limit retain by the cache in terms of your unit of size rather than by the number of entries. Once this limit is reached, the Least Recently Used entries are evicted.
In your case it’s not required to override it, unless the String object is going to store extremely long strings.
If you insist on overriding it, you may do so like this:
As the documentation says, the returned size can be an any user-defined unit. So the
String.length()would do fine. Since the size of theintis insignificant compared to the longStrings, I’ve left it out.Basically, you need to return a number that represents a relative size of an entry.