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);
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
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())));
I use this common initialization format when I anticipate changing the implementation of the List interface at a later time:
List<Foo> foos = new ArrayList<Foos>();
In an effort to gain the same utility for the values within a Map, I attempted the following but my compiler whines about List<> and ArrayList<> being incompatible types.
Map<String, List<Foo>> fooMap = new HashMap<String, ArrayList<Foo>>;
I've been unable to find an explanation for why I cannot initialize the map in this manner and I'd like to understand the reasoning.
And, sure, this works...
Map<String, List<Foo>> foosMap = new HashMap<String, List<Foo>>;
// ... populate map
ArrayList<Foo> foosAryLst = (ArrayList)foosMap.get("key1");
... but I'm a curious castaphobe. I'd rather fix compile-time errors than runtime errors, things like this aggravate my OCD and the smell of casting conjures an odor similar to the urinal trough after free deep-fried asparagus night at the stadium.
My questions come down to:
Why can I not code my map values to an interface.
Is there a workaround that doesn't require casting?
Any input will be appreciated, thanks!
Sure, there's a workaround that doesn't require casting: don't cast; write
List<Foo> foosLst = foosMap.get("key1");
...and code to the interface with the List as well as the Map.
The root issue, though, is that a Map<String, ArrayList<Foo>> isn't substitutable wherever you'd use Map<String, List<Foo>>. In particular,
Map<String, List<Foo>> map = new HashMap<>();
map.put("foo", new LinkedList<Foo>());
works, but not if map is a Map<String, ArrayList<Foo>>. So one isn't a drop-in substitute for the other.
The declaration that you proposed
Map<String, List<Foos>> fooMap = new HashMap<String, ArrayList<Foos>>();
simply does not make sense: The variable fooMap has the type Map<String, List<Foos>>. This means:
every value that you obtain from this map is a List<Foos>
you may put every value into this list that is (of a subtype of) List<Foos>
If you wanted a map that has ArrayLists as its values, then you would declare it as
Map<String, ArrayList<Foos>> fooMap = new HashMap<String, ArrayList<Foos>>();
If you don't care about the list type, then you can say
Map<String, List<Foos>> fooMap = new HashMap<String, List<Foos>>();
But there's no sensible meaning of mixing the two. Even if you could write what you proposed, then you could still not obtain an ArrayList from this map, because this is simply not the type that fooMap was declared with.
In most cases,
Map<String, List<Foos>> fooMap = new HashMap<String, List<Foos>>();
should be appropriate. Depending on the use case, one could possibly go further by saying
Map<String, List<? extends Foos>> fooMap = new HashMap<String, List<? extends Foos>>();
This way, you can also put lists into the map that contain sublcasses of Foos, like
List<SpecialFoos> specialFoos = ...
fooMap.put("special", specialFoos);
But of course, it's up to you to decide whether this is necessary or not.
The core of the problem is that the compiler cannot keep track of what fooMap may have been assigned to at any particular point in the execution of your code, so there is no way for the compiler to know that
fooMap.put("abc", new ArrayList<Foo>())
should be legal, but that
fooMap.put("abc", new LinkedList<Foo>())
should not be.
All that the compiler knows about the typing of fooMap is its declared type Map<String, List<Foo>>. So, it enforces that whatever object to which you assign fooMap must be able to support all of the operations which a generic Map<String, List<Foo>> is capable of executing. The second line of code above is clearly legal for a Map<String, List<Foo>>, but not legal for a Map<String, ArrayList<Foo>>, so the compiler forbids you from assigning fooMap to a Map<String, ArrayList<Foo>>.
I have a basic question about generics in Java: what is difference between the following two initializations of a map?
Map<String, String> maplet1 = new HashMap<String, String>();
Map<String, String> maplet2 = new HashMap();
I understand the the first initialization is specifying the generics in the object construction, but I don't understand the underlying ramifications of doing this, rather than the latter object construction (maplet2). In practice, I've always seen code use the maplet1 construction, but I don't understand where it would be beneficial to do that over the other.
The second Map is assigned to a raw type and will cause a compiler warning. You can simply use the first version to eliminate the warning.
For more see: What is a raw type and why shouldn't we use it?
The first one is type-safe.
You can shorthand the right side by using the diamond operator <>. This operator infers the type parameters from the left side of the assignment.
Map<String, String> maplet2 = new HashMap<>();
Lets understand the concept of Erasure. At RUNTIME HashMap<String, String>() and HashMap() are the same represented by HashMap.
The process of converting HashMap<String,String> to HashMap (Raw Type) is called Erasure.
Without the use of Generics , you have to cast , say the value in the Map , to String Explicitly every time.
The use of Generics forces you to Eliminate cast.
If you don't use Generics , there will be high probability that a Future Developer might insert another type of Object which will cause ClassCastException
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<>();