Java Image problem

Started by
2 comments, last by Crusable77 10 years, 6 months ago

Hello, I wrote an Image handler to read in images and then displace them appropriately. I cannot get it to work though.


        public BufferedImage getImage(String key){	
		for(String str : images.keySet()){
			if(str == key){
				System.out.println("Found " + key);
				return images.get(key);
			}
		}
		//if not found
		System.out.println("Not Found " + key);
		return images.get("error");
	}

images is a hashmap of images with a string for the key. When I run it, I always get the error image and I checked my spelling and the .txt file, and it is reading in the images. Thanks for any help.

Advertisement

In Java wouldn't you have to use .equals with strings? Otherwise you just compare the references (the pointers) which may differ.

Fruny: Ftagn! Ia! Ia! std::time_put_byname! Mglui naflftagn std::codecvt eY'ha-nthlei!,char,mbstate_t>

for(String str : images.keySet()){

if(str == key){
System.out.println("Found " + key);
return images.get(key);
}
}

You dont need to iterate the whole hashmap...

just do it:

BufferedImage image = images.get(key);

return image == null ? images.get("error") : image;

Usually in java, if you use '==' with objects you compare if the INSTANCE of the object is the same... not the content...

to use with strings it should be

string1.equals(string2)

or

string1.equalsIgnorecase(string2)

..

Btw.. dont loop a hasmap... the purpose of hashmap is to get the key as fast as possible... if you iterate over it.. the hashmap loose its purpose.

(sry about my english)

KrinosX

Thanks for the response.

This topic is closed to new replies.

Advertisement