So yeah, I'm just trying to see if there is a more elegant way of doing what I'm about to do below (please keep in mind that I want POJO (Plain-Old Java Objects) related answers, since this issue is J2ME related, so no Generics and modern data structures only found in Java 1.5 and above):
Suppose I have an object, MyImage, which just a simple bean object that gets populated with data from a network call to my server. All it contains is metadata about said image related to my app, more importantly, it contains a unique identifier that is used to construct a URL in order to fetch the image from my server for that object. I receive a new set of those objects every so often when I make a request for them, some of which are the same as previous requests.
Now, even though I am able to download the image, the problem arises in how to cache the image data in a way that when I receive a new set of MyImage objects, I cross-reference them against my cache and only retain the image for that MyImage object if it was already downloaded. In other words, when I save my downloaded image to my Hashtable cache, I key the image data with the constructed URL (MY_IMAGE_SERVER+myImageUniqueId). When I get a new set of MyImage objects, currently I do the following:
Hashtable imgs = getImages();
//If we have cached images, we should see which ones to carry over.
if(imgs.size() > 0){
Hashtable newImgs = new Hashtable();
for(int i = 0; i < myImages.length; i++){
MyImage mi = myImages[i];
if(mi != null && mi.hasImage()){
//Check if we have the MD5 URL
if(imgs.containsKey(IMG_URL_PATH + mi.getUniqueId())){
//Place in new hashtable
newImgs.put(IMG_URL_PATH + mi.getUniqueId(), imgs.get(IMG_URL_PATH + mi.getUniqueId()));
}
}
}
_bannerImgs = newImgs;
}
I am wondering if this sounds legit, or can it be done in a better more efficient way?
FOLLOWUP
Based on the assumed purpose of the code in the comment (below), the way you are doing it seems reasonable, but there are a couple of minor optimization you could make. Change the relevant part of the code to this:
// Check if we have the image in our cache
String key = IMG_URL_PATH + mi.getUniqueId();
Object image = imgs.get(key);
if (image != null) {
// Carry over to new cache
newImgs.put(key, image);
}
Note:
get
instead of contains
eliminates one hashtable lookup.However, it is doubtful that this will make a significant difference to your system's performance ... unless the getUniqueId()
method does something daft, like calculate an MD5 sum each time you call it. (And apparently it doesn't.)
Notwithstanding the performance, I'd make this change because it makes the code easier to read ... IMO.