How to Convert Int to Integer
Private Static Hashmap mBitmapCache; mBitmapCache. Put(R. Drawable. Bg1, Object); R. Drawable. Bg1 Is an Int. .. but I Want to Convert into Integer Because...
private static HashMap<Integer, Bitmap> mBitmapCache;
mBitmapCache.put(R.drawable.bg1,object);
R.drawable.bg1 is an int ... but i want to convert into Integer because Hashmap takes an Integer... and when draw the multiple objects in seconds , it creates a Integer Object runtime
which affects the performence of the code...
5 Answers
int iInt = 10;
Integer iInteger = Integer.valueOf(iInt);
P.S. Answer edited due to comments pointing out an issue with initial suggested solution.
As mentioned, one way is to use
int original = 32;
Integer converted = new Integer(original);
But you should not call the constructor for wrapper classes directly. It is a poor practice to do so. Instead, use the methods pre-defined especially for this purpose.
So, the new code would look like this (recommended):
mBitmapCache.put(Integer.valueOf(R.drawable.bg1), object);
I had a similar problem . For this you can use a Hashmap which takes "string" and "object" as shown in code below:
/** stores the image database icons */
public static int[] imageIconDatabase = { R.drawable.ball,
R.drawable.catmouse, R.drawable.cube, R.drawable.fresh,
R.drawable.guitar, R.drawable.orange, R.drawable.teapot,
R.drawable.india, R.drawable.thailand, R.drawable.netherlands,
R.drawable.srilanka, R.drawable.pakistan,
};
private void initializeImageList() {
// TODO Auto-generated method stub
for (int i = 0; i < imageIconDatabase.length; i++) {
map = new HashMap<String, Object>();
map.put("Name", imageNameDatabase[i]);
map.put("Icon", imageIconDatabase[i]);
}
}
One of the way is by using following
Integer obj = new Integer(primitiveValue)
or in your case new Integer(R.drawable.bg1).
The only problem with this is it would unnecessarily create an objects during runtime.
If you are using JDK 5 or above you can exercise power of Autoboxing.
Lets keep that aside for a while.
Within class Integer (java.lang.Integer) we do have many methods one of which is:
static Integer valueOf(int) it returns value of an int as a Integer.
So a Integer.valueOf(R.drawable.bg1) could work.
i it integer, int to Integer
Integer intObj = new Integer(i);
add to collection
list.add(String.valueOf(intObj));