Can I define a hashmap differently to it's declaration - java

What I would like to do is have a map that actually holds values as one thing, but is declared as another e.g. actually hold the value as String, but put/get will use Integer...
Map<String,String> map = new HashMap<String,String>();
I can use this map with
map.put("A","1");
String ret = map.get("A");
but this will get me a String, and I need to 'put' in a String too.
What I would like is for the put/get methods to accept an Integer value (but the map still stores ...
map.put("A",1);
Integer ret = map.get("A");
How can I achieve this?
N.B. this isn't exclusively for String/Integer conversion, but just conversion between any types.
Thanks.

You can use Object as the value type. It can store String, Integer, Double, for that matter almost anything. But you need to be very careful when using Object because you'll have to cast each value you get from the map accordingly(else you'll always get a ClassCastException).
Map<String, Object> map = new HashMap<String, Object>();
FYI, I do not recommended you to use this. Instead be sure what your Map has to hold and have the value type accordingly.

Simply
Map<String,Integer> map = new HashMap<String,Integer>();

You can (but not SHOULD use, really) this critter: https://gist.github.com/eltabo/8953176. Really... it's evil.
Only for educational purpose.

Why should someone want to store a value in a different representation than the value is made out of? You still can create a string out of an integer and reverse after obtaining it from the map, but what is your advantage?

Related

Using the same HashMapM<String,....> for String and array of String (String[])

I have some attributes that are of the type String, and the type "ArrayString" (String[]). How can I put then in the same HashMap?
Example:
String data;
String[] array;
... // Initialize and put the values in attributes
HashMap <String, *> hm = new HashMap<String, *> // * -> it's what i want
hm.put ("data", data);
hm.put("array", array);
Which value, or class, must be in *?
Personally, I'd go about it a different way - always store the values as String[], and if you have a single value just store it in an array with a single element). It would make your code considerably simpler.
If you absolutely must mix Strings and String[]s, you can only use Object as the value type (i.e., HashMap<String, Object>, and will have to use runtime type identification in your code.
you can use
HashMap<String, List<String>>
instead to accomplish your goals. If this doesn't suit you please provide more context and I'd be glad to help

Hashmap not allowing integer as value

My situation demands to add Integer to the Hashmap value because i need to sort the list based on the integer. I am doing like below
Map hmInspStatus = new HashMap();
hmInspStatus.put("Name",Integer.parseInt(strIRName.substring(2,strIRName.length())));
System is throwing an error message saying i can't add an integer to a HashMap. I referred some of the posts in the site and suggested to use a HashSet, but is it possible to add Key, value to HashSet?
Can anybody help me in achieving what i am looking for?
Thanks
Modern Java uses generic data structures. With the generic types given, Java will handle autoboxing of the primitive type.
Map<String, Integer> hmInspStatus = new HashMap<String, Integer>();
hmInspStatus.put("Name",Integer.parseInt(strIRName.substring(2,strIRName.length())));
Update: OP is using Java 1.3. This version not only does not support generics, it also does not support autoboxing. In that case, you have to skip the generics and use manual boxing, or directly construct the Integer from the String.
Map hmInspStatus = new HashMap();
hmInspStatus.put("Name", new Integer(strIRName.substring(2,strIRName.length())));
Do:
Map hmInspStatus = new HashMap();
hmInspStatus.put("Name",(Integer)Integer.parseInt(strIRName.substring(2,strIRName.length())));

Grab object where key is a certain value

Within my java application I have a hashmap that holds a string and an Integer. I'm in a situation where I need to return an object where the key is a certain value. I'm not sure how I would go about doing this. Your support would be greatly appreciated.
public HashMap<String, Integer> loginArenaList = new HashMap();
You need Map#get(Object) method:
loginArenaList.get(key);
BTW, your declaration of map is wrong. You are missing generics type on RHS. And of course, you should declare the reference as private, unless you have strong reasons to use public. Should be:
private Map<String, Integer> loginArenaList = new HashMap<>(); // In Java 7
According to the declared map, your keys are of type String and the object to be retrieved is of type Integer. Assuming that you have the key in the variable "key", all you have to do is use the get method.
loginArenaList.get(key);

Is there any KV data structure in Java which accepts key in primitive type?

I need to store information in Key Value manner. But the built-in Map interface cannot fit for my requirement. Java Map requires both Key and Values to be reference, while I need to use primitive value as key.
Is there any data structure something like Map ? Thanks for your help!
Requirement Details:
My server written in Java runs as a daemon listening a tcp port. When a user first connect in, details about the user need to be stored in KV manner, and the second time the user connect in, his details should be able to read from the KV data structure.
I cannot use the user object as key, for it will be destructed when disconnect, and reconstructed in the second connection. The two objects are not the same reference. Integer key doesn't fit for my requirement either for the same reason.
In other words, I need to use value as key, not reference.
Keys could be considered are: UUID(long), id(int) and so on. They are all primitive type.
Still you can go with java Map as wrapper classes are available for all primitive type and java supports auto boxing, So you can use java.util.Map. ex -
Map<Long,Integer> map = new HashMap<Long,Integer>();
long uuid=10; int i= 10;
map.put(uuid,i);
I fail to see why you can't simply wrap your primitive type in it's corresponding non-primitive class and use that as your key in a regular java map.
Map<Integer, Object> map = new HashMap<Integer, Object>();
Integer key = Integer.valueOf(5);
Object test = new Object();
map.put(key, test);
Object test2 = map.get(Integer.valueOf(5));
test.equals(test2); // will be true
No, collections don't suport primitive types, so you have to use a wrapper classes for primitive types or array.
What you are looking for is called a Hashmap.
Hashmap<Long, Integer> dict=new HashMap<Long, Integer>();
dict.put(24,10);
dict.put(13,63);
dict.get(13); // Equals 63
Essentially, a HashMap will take the first argument as a key, and the second as the value, exactly as you requested. You can assign any type, including a Long for larger integers than normal, although you can't pass primitives. Still, this hasn't ever been an issue for me.
various implementations exist elsewhere, but not in the standard java library. See for example LongHashMap.
The HashMap class is fine for using key-value pairs, but there is no such thing which accepts primitive types.
We'll still try to use a primitive type in the context of a Map.
HashMap<Integer, V> map = new HashMap<>();
map.put(12, someV);
As we write map.put(12, someV), in fact, one cannot use a primitive type as the first argument of the method 'put' of class java.util.Map. But in Java, the integer '12' will automatically be 'converted' (auto-boxed) into the correspondenting wrapper class, in this case Integer.
So that means that there is actually an object of type Integer in the HashMap, but it is reflected as an int.

Cannot Create an LinkedList<String, int>

i want to create an LinkedList of couple that the key is a String and the value is an integer ?
LinkedList doesn't have a key. It's a list of elements, not a key/value mapping.
If you want a LinkedList where each element is a pair of Integer/String values, you'll need to pick one of:
Create a generic Pair class
(Ab)use an existing generic class (e.g. Map.Entry)
Create a custom class for your specific scenario
I would suggest the last option as the most sensible one - you'll be able to give it appropriate semantics and names according to the real meaning of the string and the integer. Heck, you'll also be able to avoid boxing the integer, as you can have:
public class WhateverYouCallIt {
private final int firstValue;
private final String secondValue;
// Constructor, properties
}
You can only use Object in a LinkedList., this means you cant use Java Primitives.
However, what you seem to need is a Map structure.
I recommend using java.util.HashMap, it allows you to create a Key, Value pairs.
Example:
HashMap<String,Integer> a = new HashMap<String,Integer>();
a.put("one",1);
a.put("two",2);
System.out.println(a.get("one"));
//prints 1
System.out.println(a.get("two"));
//prints 2
EDIT:
As per your comment, i see you required order, use the following example then:
LinkedHashMap<String, Integer> b = new LinkedHashMap<String,Integer>();
b.put("one",1);
b.put("two",2);
b.put("a",3);
for (String key:b.keySet())
{
System.out.println(b.get(key)); // print 1 then 2 finally 3
}
Hope this is what you were asking (if so, modify your question).
One error is you need Integer instead of int, but as others have pointed out LinkedList doesn't take Key/Value pairs.
I'd imagine a HashMap is what your after. As other have stated, you cannot use a primitive type such as "int" in a library storage class like LinkedList, or ArrayList, you must instead use an object such as "Integer".
HashMap hash = new HashMap();
Read this for more information: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html

Categories

Resources