Eclipse Warning with Java HashMap - java

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<>();

Related

How do I implement a hashmap using generics? (Issue with not being able to create generic arrays) [duplicate]

In the Java implementation, I found
transient Entry[] table;
which is initiated in constructor as
table = new Entry[capacity];
I know and understand that creating generic array is not allowed but then what I fail to understand is that how the whole thing works. I mean when we do something like
HashMap<Integer, String> hMap = new HashMap<Integer, String>();
How does above codes leads to creating an Entry array of type <Integer, String>
Well, few people are not able to understand what I am asking. To rephrase what I am asking is what is the point in doing something like
HashMap<Integer, String> hMap = new HashMap<Integer, String>();
When it does not result in
Entry<Integer, String>
Generics are a compile-time safety. At runtime, the map only know about Objects. This is known as type erasure. To scare you even more, the following code will run without problem:
Map<Integer, Integer> safeMap = new HashMap<>();
Map unsafeMap = safeMap;
unsafeMap.put("hello", "world");
You'll get a warning at compile time, because you're using a raw Map instead of a generic one, but at runtime, no check is done at all, because the map is a good old map able of storing any object. Only the compiler prevents you from adding Strings in a map or integers.
The implementation makes an array of Entry<K,V> objects of type
static class Entry<K,V> implements Map.Entry<K,V>
without providing generic type parameters (source). This is allowed, but it comes with understanding that the compiler is no longer guarantees type safety. For example, in other places in code you could write
Entry<K,V> e = table[bucketIndex];
and the compiler will let you do that. If you know for sure that you always set elements of table[] to null or Entry<K,V>, then you know that the assignment is correct.
The reason this works without a problem is that generic types in Java are implemented through type erasure, i.e. there is no difference at runtime between Entry<K,V> objects Entry<Integer,Integer> and Entry<String,Long>.
Try to think of Java Generics this way: type parameters only apply to the static type of reference-typed expressions and do not apply to the type of actual instances being referred to by the reference values at runtime.
I find the above key to developing the proper intuitions when reading Java code. So the next time you see
new HashMap<Integer, String>()
read it as follows: "This is an instance creation expression of the type HashMap<Integer, String>. At runtime this expression will yield a reference to an instance of the HashMap class." As long as the compiler can precisely track what you do with the result of that expression, it can maintain the knowledge that this is indeed a HashMap<Integer, String>, but no further than that.
Now, since the static type system is not powerful enough to track the type parameters on the component type of arrays (the fact that Java's array types are covariant plays strongly here), the code is forced to break out of the static type safety network. The key observation is that on its own, this does not make the code incorrect, it only constrains the power of the compiler to find programming mistakes. This is why Java allows you to make unchecked casts from raw into generic types, although not without a warning which marks the spot where you have left the provinces of static type safety.

Generics in HashMap implementation

In the Java implementation, I found
transient Entry[] table;
which is initiated in constructor as
table = new Entry[capacity];
I know and understand that creating generic array is not allowed but then what I fail to understand is that how the whole thing works. I mean when we do something like
HashMap<Integer, String> hMap = new HashMap<Integer, String>();
How does above codes leads to creating an Entry array of type <Integer, String>
Well, few people are not able to understand what I am asking. To rephrase what I am asking is what is the point in doing something like
HashMap<Integer, String> hMap = new HashMap<Integer, String>();
When it does not result in
Entry<Integer, String>
Generics are a compile-time safety. At runtime, the map only know about Objects. This is known as type erasure. To scare you even more, the following code will run without problem:
Map<Integer, Integer> safeMap = new HashMap<>();
Map unsafeMap = safeMap;
unsafeMap.put("hello", "world");
You'll get a warning at compile time, because you're using a raw Map instead of a generic one, but at runtime, no check is done at all, because the map is a good old map able of storing any object. Only the compiler prevents you from adding Strings in a map or integers.
The implementation makes an array of Entry<K,V> objects of type
static class Entry<K,V> implements Map.Entry<K,V>
without providing generic type parameters (source). This is allowed, but it comes with understanding that the compiler is no longer guarantees type safety. For example, in other places in code you could write
Entry<K,V> e = table[bucketIndex];
and the compiler will let you do that. If you know for sure that you always set elements of table[] to null or Entry<K,V>, then you know that the assignment is correct.
The reason this works without a problem is that generic types in Java are implemented through type erasure, i.e. there is no difference at runtime between Entry<K,V> objects Entry<Integer,Integer> and Entry<String,Long>.
Try to think of Java Generics this way: type parameters only apply to the static type of reference-typed expressions and do not apply to the type of actual instances being referred to by the reference values at runtime.
I find the above key to developing the proper intuitions when reading Java code. So the next time you see
new HashMap<Integer, String>()
read it as follows: "This is an instance creation expression of the type HashMap<Integer, String>. At runtime this expression will yield a reference to an instance of the HashMap class." As long as the compiler can precisely track what you do with the result of that expression, it can maintain the knowledge that this is indeed a HashMap<Integer, String>, but no further than that.
Now, since the static type system is not powerful enough to track the type parameters on the component type of arrays (the fact that Java's array types are covariant plays strongly here), the code is forced to break out of the static type safety network. The key observation is that on its own, this does not make the code incorrect, it only constrains the power of the compiler to find programming mistakes. This is why Java allows you to make unchecked casts from raw into generic types, although not without a warning which marks the spot where you have left the provinces of static type safety.

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())));

Understanding Generics in Object Initialization

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

serialize/deserialize a LinkedHashMap (android) java

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);

Categories

Resources