Paweł
Paweł

Reputation: 2234

Create HashMap as cache for objects, problem with key object

I'm new to java, i'm working width android sdk

Im generating a lot of objects which are in 50% te same so i thought that i can implement a simple caching mechanism

private HashMap<CachePathKey, Path> mCachedPaths;



public Path GenerateRealPath(final Sprite pSprite,final int pStartIndex){

    CachePathKey mCachedKey = new CachePathKey(mPathID, pStartIndex, MyGame.mCamera.getZoomFactor(), pSprite.getWidth(), pSprite.getHeight());

    if (!mCachedPaths.containsKey(mCachedKey)){
       //generate Path Object to p 
       mCachedPaths.put(mCachedKey,p);
       return p;
    } else {
       return mCachedPaths.get(mCachedKey);
    }

and the CachePathKey is :

class CachePathKey {
private int mPathID;
private int mStartIndex;
private float mZF;
private float mWidthSprite;
private float mHeightSprite;
public CachePathKey(int pPathID, int pStartIndex, float pZf,
        float pWidthSprite, float pHeightSprite) {
    this.mPathID =pPathID;
    this.mStartIndex = pStartIndex;
    this.mZF = pZf;
    this.mWidthSprite = pWidthSprite;
    this.mHeightSprite = pHeightSprite;
}
}

but i've nulls as keys when debugging, and containsKey returning always false

what i'm doing wrong ?

Upvotes: 0

Views: 553

Answers (2)

Manuel Selva
Manuel Selva

Reputation: 19050

The code you posted can't leads to null keys in the mCachedPaths map. Thus you should look outside from this code to see who is putting these null keys.

You also have to override Equals and HashCode methods in your CachePathKey class using the mPathID and the mZf fields (the fields that makes your object unique). IDE such has eclipse allows you (from contextual menu in Eclipse) to automatically override these methods using end user selected class members.

I also strongly recommend the reading of Chapter9 in Effective Java 2nd edition book.

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240860

you need to override equals and hashcode method for CachePathKey,

Since you have unique identified for object do a equal test on mPathID

Upvotes: 1

Related Questions