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())));
Related
So I'm working on a plugin for Atlassian Confluence and in my controller for the configuration page I have a HashMap of Type HashMap<Integer, String> that I fill with values from a HTML form. Now after submitting the form, I try to read a value from that HashMap with .get(key) and safe that to a String. I get this typecasting error: java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String. So I looked at the values with a debugger and sure enough my HashMap contains strings wrapped in arrays of length 1 instead of plain simple strings: even tough my HashMap clearly is defined with types Integer->String and the assignment to String works without any explicit typecasting. This is really confusing me. I guess it has to do with the Atlassian stuff automagically deserializing POST-Values; in the past this has already cost me quite a lot of headaches, as there is no proper documentation and the magical background conversion has quite a lot of quirks. What really confuses me tough is the fact that the HashMap can suddenly store values of a different type than defined, I wouldn't have thought it possible with Java putting such a focus on type safety. Is there some reflection foo that can do this, that I'm unaware of? Or am I misunderstanding the nature of HashMaps? Anybody ever experienced something similar? I'm not that experienced at coding in Java.
In case you are creating hashmap as HashMap<Integer, String>() but storing it as HashMap it is indeed possible to store there other types.
For example:
HashMap map = new HashMap<Integer, String>();
map.put(1, new String[]{"1", "2"});
System.out.println(map.get(1));
This code executes without any errors.
So I think what happens is that in you are storing it just as a HashMap reference which is treated as HashMap<Object, Object> and as there is no runtime information about actual generic types you are able to add objects of other types to this collection.
But if you have another reference to the same map with HashMap<Integer, String> then when you call, for example, get(), it would fail with exception you described:
HashMap map = new HashMap<Integer, String>();
map.put(1, new String[]{"1", "2"});
System.out.println(map.get(1));
System.out.println("got here");
HashMap<Integer, String> otherRef = (HashMap<Integer, String>) map;
System.out.println(otherRef.get(1)); //<-ClassCastException exception here
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?
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.
Eclipse is saying "HashMap is a raw type" When I use the following code
HashMap = new HashMap();
Any idea what could be wrong?
Eclipse will give you that warning when you use a non-Generic HashMap using Java 5 or newer.
See Also: The Generics Lesson in Sun's Java Tutorials.
Edit: Actually, here, I'll give an example too:
Say I want to map someone's name to their Person object:
Map<String, Person> map = new HashMap<String, Person>();
// The map.get method now returns a Person
// The map.put method now requires a String and a Person
These are checked at compile-time; the type information is lost at run-time due to how Java implements Generics.
Nothing wrong exactly, but you are missing out on the wonderful world of generics. Depending on what constraints you want to place on the types used in your map, you should add type parameters. For example:
Map<String, Integer> map = new HashMap<String, Integer>();
That is missing generics, i.e. . If you don't know thise then set the eclipse compiler to java 1.4
Try
HashMap<String,Integer> map = new HashMap<String,Integer>();
instead (obviously replacing the key type (String) and value type (Integer)).
That usually means you're mixing generic code with non-generic code.
But as your example wont even compile its rather hard to tell....
It's missing the generic type. You should specify the key-value generic pair for your map. For instance, the following is a declaration that instantiates a HashMap with String type key and Integer type value.
Map<String, Integer> map = new HashMap<String, Integer>();
All of these are valid answers, you could also use the #SurpressWarnings annotation to get the same result, without having to resort to actual generics. ;)
hashmap is a raw type and hence should be parameterised ie
what ever the data we get through the haspmap function their type must be declared for getting its functions
for example
HashMap<String, Integer> map = new HashMap<String, Integer>();
With the latest Java, you do not have to explicitly mention the variable types in declaration. You can simply put:
= new HashMap<>();
So i want to pass a LinkedHashMap to an intent.
//SEND THE MAP
Intent singlechannel = new Intent(getBaseContext(),singlechannel.class);
singlechannel.putExtra("db",shows1);//perase to
startActivity(singlechannel);
//GET THE MAP
LinkedHashMap<String,String> db = new LinkedHashMap<String,String>();
db=(LinkedHashMap<String,String>) getIntent().getSerializableExtra("db");
This one Worked Like a charm with HashMap.
But with LinkedHashMap i got a problem i got a runtime error here
db=(LinkedHashMap<String,String>) getIntent().getSerializableExtra("db");
I get no error with HashMap.
I also got a warning "Type safety: Unchecked cast from Serializable to LinkedHashMap"
But i had this warning with HashMap too.
Any ideas.Any help is much appreciated
Also I just saw this.
https://issues.apache.org/jira/browse/HARMONY-6498
The root of the problem here is that you are trying to type cast to a generic type. This cannot be done without an unsafe/unchecked type cast.
The runtime types of generic types are raw types; i.e. types in which the actual types of the type parameters are not known. In this case the runtime type will be LinkedHashMap<?, ?>. This cannot be safely typecast to LinkedMashMap<String, String> because the runtime system has no way of knowing that all of the keys and values are actually String instances.
You have two options:
You could add an annotation to tell the compiler to "shut up" about the unchecked cast. This is a bit risky. If for some reason one of the keys or values is not actually a String, your application may later get a ClassCastException at a totally unexpected place; e.g. while iterating the keys or assigning the result of a get.
You could manually copy the deserialised Map<?, ?> into a new LinkedMashMap<String, String>, explicitly casting each key and value to String.
UPDATE
Apparently the real cause of the runtime exception (as distinct from the "unsafe typecast" compilation error) is that Android is passing the serializedExtra between intents as a regular HashMap rather than using the Map class that you provided. This is described here:
Sending LinkedHashMap to intent.
As that Q&A explains, there is no simple workaround. If you want to pass a map preserving the key order, will have to convert the map to an array of pairs and pass that. On the other end, you will then need to reconstruct the map from the passed array.
LinkedHashMap does implement Map interface, here is definition from the source code:
public class LinkedHashMap<K,V>
extends HashMap<K,V>
implements Map<K,V>
The following test is working fine, so I think the problem you have is not related LinkedHashMap.
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("1", "one");
FileOutputStream fos = new FileOutputStream("c://map.ser");
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(map);
out.close();
FileInputStream fin = new FileInputStream("c://map.ser");
ObjectInputStream in = new ObjectInputStream(fin);
Map<String, String> map2 = (Map<String, String>) in.readObject();
System.out.println(map2);