Restricting the Object Type for the get method in a Java HashMap [duplicate]What are the reasons why Map.get(Object key) is not (fully) genericWhy aren't Java Collections remove methods generic?Does a finally block always get executed in Java?Fastest way to determine if an integer's square root is an integerA Java collection of value pairs? (tuples?)How to get an enum value from a string value in Java?Java Hashmap: How to get key from value?get string value from HashMap depending on key nameHow to update a value, given a key in a java hashmap?java.lang.OutOfMemoryError: GC overhead limit exceededRestrict HashMap to accept a particular string keyWhy does Map.of not allow null keys and values?

Binary Numbers Magic Trick

Can a cyclic Amine form an Amide?

How did Captain America use this power?

Write to EXCEL from SQL DB using VBA script

Is there a QGIS plugin that reclassify raster symbology based on current extent?

When and why did journal article titles become descriptive, rather than creatively allusive?

When do aircrafts become solarcrafts?

Why was Germany not as successful as other Europeans in establishing overseas colonies?

How to efficiently calculate prefix sum of frequencies of characters in a string?

How to get SEEK accessing converted ID via view

How to avoid grep command finding commented out strings in the source file?

If I supply 24v to a 50v rated 22000uf electrolytic capacitor, does that mean it will store 44000uf at 24v?

Public Salesforce Site and Security Review

Why debootstrap can only run as root?

How do I tell my manager that his code review comment is wrong?

Why is Arya visibly scared in the library in S8E3?

Transfer over $10k

Conflicting terms and the definition of a «child»

What does air vanishing on contact sound like?

What word means "to make something obsolete"?

Game of Life meets Chaos Theory

If Melisandre foresaw another character closing blue eyes, why did she follow Stannis?

Entropy as a function of temperature: is temperature well defined?

Pressure to defend the relevance of one's area of mathematics



Restricting the Object Type for the get method in a Java HashMap [duplicate]


What are the reasons why Map.get(Object key) is not (fully) genericWhy aren't Java Collections remove methods generic?Does a finally block always get executed in Java?Fastest way to determine if an integer's square root is an integerA Java collection of value pairs? (tuples?)How to get an enum value from a string value in Java?Java Hashmap: How to get key from value?get string value from HashMap depending on key nameHow to update a value, given a key in a java hashmap?java.lang.OutOfMemoryError: GC overhead limit exceededRestrict HashMap to accept a particular string keyWhy does Map.of not allow null keys and values?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








11
















This question already has an answer here:



  • What are the reasons why Map.get(Object key) is not (fully) generic

    11 answers



I have instantiated my HashMap like this:



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


The datatype of the Key is String, so when I try to insert a new key-value pair in the map keeping the Key as Integer, it throws an error.



myHashMap.put(1L, "value");


That means in the put method they have restricted the datatype of the Key. But while fetching the value from the map using the get method it is not checking for the datatype of the Key. So if I write something like this, it doesn't give a compilation error.



myHashMap.get(1L);


I checked the get method in the Java Map interface and its parameter type is Object, so that's why it is allowing any Object as the put method argument.



V get(Object key)


Is there a way I can restrict the datatype which I pass as an argument in the get method?



The argument that I pass should have the same datatype as the datatype of the Key which I use while instantiating my hashmap.










share|improve this question















marked as duplicate by Roddy of the Frozen Peas, KevinO, Community Apr 22 at 19:05


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.













  • 1





    No. But good IDEs will warn you when doing that. And you can encapsulate the map into your own class.

    – JB Nizet
    Apr 22 at 7:16











  • In other languages you could create extension method, like getTyped.... In Java you can do this with static method, so your call will be getTyped(map, key). Ugly, but works.

    – dyukha
    Apr 22 at 7:22












  • I have considered the option of creating a wrapper method over the get method, something like this: Integer getMapValue(Map map, String Key) return map.get(key) And call this method instead of the get method, but I wanted to know if Java provides any such restricting feature of not?

    – Rito
    Apr 22 at 7:30











  • You can add an implementation of a get(K key) method, but It seems like an unnecessary effort. The return value for a mismatching key (type-wise) will be null, as expected. So the Map will conform to its API.

    – Rann Lifshitz
    Apr 22 at 7:37

















11
















This question already has an answer here:



  • What are the reasons why Map.get(Object key) is not (fully) generic

    11 answers



I have instantiated my HashMap like this:



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


The datatype of the Key is String, so when I try to insert a new key-value pair in the map keeping the Key as Integer, it throws an error.



myHashMap.put(1L, "value");


That means in the put method they have restricted the datatype of the Key. But while fetching the value from the map using the get method it is not checking for the datatype of the Key. So if I write something like this, it doesn't give a compilation error.



myHashMap.get(1L);


I checked the get method in the Java Map interface and its parameter type is Object, so that's why it is allowing any Object as the put method argument.



V get(Object key)


Is there a way I can restrict the datatype which I pass as an argument in the get method?



The argument that I pass should have the same datatype as the datatype of the Key which I use while instantiating my hashmap.










share|improve this question















marked as duplicate by Roddy of the Frozen Peas, KevinO, Community Apr 22 at 19:05


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.













  • 1





    No. But good IDEs will warn you when doing that. And you can encapsulate the map into your own class.

    – JB Nizet
    Apr 22 at 7:16











  • In other languages you could create extension method, like getTyped.... In Java you can do this with static method, so your call will be getTyped(map, key). Ugly, but works.

    – dyukha
    Apr 22 at 7:22












  • I have considered the option of creating a wrapper method over the get method, something like this: Integer getMapValue(Map map, String Key) return map.get(key) And call this method instead of the get method, but I wanted to know if Java provides any such restricting feature of not?

    – Rito
    Apr 22 at 7:30











  • You can add an implementation of a get(K key) method, but It seems like an unnecessary effort. The return value for a mismatching key (type-wise) will be null, as expected. So the Map will conform to its API.

    – Rann Lifshitz
    Apr 22 at 7:37













11












11








11


2







This question already has an answer here:



  • What are the reasons why Map.get(Object key) is not (fully) generic

    11 answers



I have instantiated my HashMap like this:



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


The datatype of the Key is String, so when I try to insert a new key-value pair in the map keeping the Key as Integer, it throws an error.



myHashMap.put(1L, "value");


That means in the put method they have restricted the datatype of the Key. But while fetching the value from the map using the get method it is not checking for the datatype of the Key. So if I write something like this, it doesn't give a compilation error.



myHashMap.get(1L);


I checked the get method in the Java Map interface and its parameter type is Object, so that's why it is allowing any Object as the put method argument.



V get(Object key)


Is there a way I can restrict the datatype which I pass as an argument in the get method?



The argument that I pass should have the same datatype as the datatype of the Key which I use while instantiating my hashmap.










share|improve this question

















This question already has an answer here:



  • What are the reasons why Map.get(Object key) is not (fully) generic

    11 answers



I have instantiated my HashMap like this:



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


The datatype of the Key is String, so when I try to insert a new key-value pair in the map keeping the Key as Integer, it throws an error.



myHashMap.put(1L, "value");


That means in the put method they have restricted the datatype of the Key. But while fetching the value from the map using the get method it is not checking for the datatype of the Key. So if I write something like this, it doesn't give a compilation error.



myHashMap.get(1L);


I checked the get method in the Java Map interface and its parameter type is Object, so that's why it is allowing any Object as the put method argument.



V get(Object key)


Is there a way I can restrict the datatype which I pass as an argument in the get method?



The argument that I pass should have the same datatype as the datatype of the Key which I use while instantiating my hashmap.





This question already has an answer here:



  • What are the reasons why Map.get(Object key) is not (fully) generic

    11 answers







java hashmap






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 22 at 13:50









Peter Mortensen

14k1987114




14k1987114










asked Apr 22 at 7:04









RitoRito

1,117819




1,117819




marked as duplicate by Roddy of the Frozen Peas, KevinO, Community Apr 22 at 19:05


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by Roddy of the Frozen Peas, KevinO, Community Apr 22 at 19:05


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









  • 1





    No. But good IDEs will warn you when doing that. And you can encapsulate the map into your own class.

    – JB Nizet
    Apr 22 at 7:16











  • In other languages you could create extension method, like getTyped.... In Java you can do this with static method, so your call will be getTyped(map, key). Ugly, but works.

    – dyukha
    Apr 22 at 7:22












  • I have considered the option of creating a wrapper method over the get method, something like this: Integer getMapValue(Map map, String Key) return map.get(key) And call this method instead of the get method, but I wanted to know if Java provides any such restricting feature of not?

    – Rito
    Apr 22 at 7:30











  • You can add an implementation of a get(K key) method, but It seems like an unnecessary effort. The return value for a mismatching key (type-wise) will be null, as expected. So the Map will conform to its API.

    – Rann Lifshitz
    Apr 22 at 7:37












  • 1





    No. But good IDEs will warn you when doing that. And you can encapsulate the map into your own class.

    – JB Nizet
    Apr 22 at 7:16











  • In other languages you could create extension method, like getTyped.... In Java you can do this with static method, so your call will be getTyped(map, key). Ugly, but works.

    – dyukha
    Apr 22 at 7:22












  • I have considered the option of creating a wrapper method over the get method, something like this: Integer getMapValue(Map map, String Key) return map.get(key) And call this method instead of the get method, but I wanted to know if Java provides any such restricting feature of not?

    – Rito
    Apr 22 at 7:30











  • You can add an implementation of a get(K key) method, but It seems like an unnecessary effort. The return value for a mismatching key (type-wise) will be null, as expected. So the Map will conform to its API.

    – Rann Lifshitz
    Apr 22 at 7:37







1




1





No. But good IDEs will warn you when doing that. And you can encapsulate the map into your own class.

– JB Nizet
Apr 22 at 7:16





No. But good IDEs will warn you when doing that. And you can encapsulate the map into your own class.

– JB Nizet
Apr 22 at 7:16













In other languages you could create extension method, like getTyped.... In Java you can do this with static method, so your call will be getTyped(map, key). Ugly, but works.

– dyukha
Apr 22 at 7:22






In other languages you could create extension method, like getTyped.... In Java you can do this with static method, so your call will be getTyped(map, key). Ugly, but works.

– dyukha
Apr 22 at 7:22














I have considered the option of creating a wrapper method over the get method, something like this: Integer getMapValue(Map map, String Key) return map.get(key) And call this method instead of the get method, but I wanted to know if Java provides any such restricting feature of not?

– Rito
Apr 22 at 7:30





I have considered the option of creating a wrapper method over the get method, something like this: Integer getMapValue(Map map, String Key) return map.get(key) And call this method instead of the get method, but I wanted to know if Java provides any such restricting feature of not?

– Rito
Apr 22 at 7:30













You can add an implementation of a get(K key) method, but It seems like an unnecessary effort. The return value for a mismatching key (type-wise) will be null, as expected. So the Map will conform to its API.

– Rann Lifshitz
Apr 22 at 7:37





You can add an implementation of a get(K key) method, but It seems like an unnecessary effort. The return value for a mismatching key (type-wise) will be null, as expected. So the Map will conform to its API.

– Rann Lifshitz
Apr 22 at 7:37












2 Answers
2






active

oldest

votes


















17














It is designed that way, since during the get operation only the equals and hashCode is used to determine the object to be returned. The implementation of the get method does not check for the type of the Object used as the key.



In your example you are trying to get the value by passing a long like myHashMap.get(1L);, firstly the hash code of the object Long having the value 1L will be used to determine the bucket from which to look for. Next the equals method of the key is used to find out the exact entry of the map from which to return the value. And in a well-defined equals method there is always a check for the type:



public boolean equals(Object obj) 
if (obj instanceof Long) //here type is checked
return value == ((Long)obj).longValue();

return false;



So if the types are not equal, the equals method returns false and hence get also will return null.



In some cases such as when using List as a key, it may happen that you put an item in the map using an instance of say an ArrayList but you can successfully retrieve the same value with an instance of an LinkedList. As both implement the List interface.



Map<List<String>, String> myHashMap = new HashMap<>();
List<String> arrayList = new ArrayList<>();
List<String> linkedList = new LinkedList<>();
myHashMap.put(arrayList, "foo");
System.out.println(myHashMap.get(linkedList));


The above code will output in the console foo.



Here although the implementations are different but if you examine the equals method of ArrayList, it is only checking if the type is a List:



public boolean equals(Object o) 
if (o == this)
return true;


if (!(o instanceof List)) //checking type of super interface
return false;

...



The same is true for LinkedList.






share|improve this answer




















  • 2





    This is a good example of how an answer should be written in StackOverflow - well formulated, informative, with to-the-point code examples. Well done!

    – Rann Lifshitz
    Apr 22 at 8:04






  • 1





    This answer is failing to address the "compilation error" aspect of the question and missing the implicit question of why Map.get is declared to accept Object instead of the K parameterized type.

    – Miles
    Apr 22 at 9:53






  • 1





    @Miles that question has already been answered here and here.

    – Moira
    Apr 22 at 14:11












  • As per the first link @Moira posted the List example should have the map type be something like Map<ArrayList<String>, String> instead. If the key type is List<String> then V get(K key) will still work and compile fine with both ArrayList and LinkedList. Also this answer does not attempt to answer OP's actual question "Is there a way I can restrict the datatype which I pass as an argument in the get method?"

    – SamYonnou
    Apr 22 at 15:03







  • 1





    @SamYonnou with a map defined like this Map<ArrayList<String>, String>, get with a LinkedList<String> instance would still work and retrieve the correct value as in the equals method the instanceof is done w.r.t to List and both ArrayList and LinkedList instances would satisfy that as I mentioned in my answer. And for the actual question many people have already pointed out that it is unnecessary and provided sample code to do it either way. I also explained that with a well defined equals method why it won't be necessary. :)

    – Amardeep Bhowmick
    Apr 22 at 15:32


















4














I think if it is very important in a project that we control type in HashMap, we could extend HashMap and force using this class instead of HashMap like the below code.



We have all HashMap capabilities, and we should just use the getValue method instead of the get method.



import java.util.HashMap;

public class MyHashMap<K,V> extends HashMap<K,V>

public V getValue(K key)
return super.get(key);




Test class:



 public class Test 
public static void main(String[] args)
MyHashMap<String,Integer> map = new MyHashMap();







share|improve this answer




















  • 2





    A similar answer was posted maybe an hour ago and was then deleted by its poster...........

    – Rann Lifshitz
    Apr 22 at 8:02

















2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









17














It is designed that way, since during the get operation only the equals and hashCode is used to determine the object to be returned. The implementation of the get method does not check for the type of the Object used as the key.



In your example you are trying to get the value by passing a long like myHashMap.get(1L);, firstly the hash code of the object Long having the value 1L will be used to determine the bucket from which to look for. Next the equals method of the key is used to find out the exact entry of the map from which to return the value. And in a well-defined equals method there is always a check for the type:



public boolean equals(Object obj) 
if (obj instanceof Long) //here type is checked
return value == ((Long)obj).longValue();

return false;



So if the types are not equal, the equals method returns false and hence get also will return null.



In some cases such as when using List as a key, it may happen that you put an item in the map using an instance of say an ArrayList but you can successfully retrieve the same value with an instance of an LinkedList. As both implement the List interface.



Map<List<String>, String> myHashMap = new HashMap<>();
List<String> arrayList = new ArrayList<>();
List<String> linkedList = new LinkedList<>();
myHashMap.put(arrayList, "foo");
System.out.println(myHashMap.get(linkedList));


The above code will output in the console foo.



Here although the implementations are different but if you examine the equals method of ArrayList, it is only checking if the type is a List:



public boolean equals(Object o) 
if (o == this)
return true;


if (!(o instanceof List)) //checking type of super interface
return false;

...



The same is true for LinkedList.






share|improve this answer




















  • 2





    This is a good example of how an answer should be written in StackOverflow - well formulated, informative, with to-the-point code examples. Well done!

    – Rann Lifshitz
    Apr 22 at 8:04






  • 1





    This answer is failing to address the "compilation error" aspect of the question and missing the implicit question of why Map.get is declared to accept Object instead of the K parameterized type.

    – Miles
    Apr 22 at 9:53






  • 1





    @Miles that question has already been answered here and here.

    – Moira
    Apr 22 at 14:11












  • As per the first link @Moira posted the List example should have the map type be something like Map<ArrayList<String>, String> instead. If the key type is List<String> then V get(K key) will still work and compile fine with both ArrayList and LinkedList. Also this answer does not attempt to answer OP's actual question "Is there a way I can restrict the datatype which I pass as an argument in the get method?"

    – SamYonnou
    Apr 22 at 15:03







  • 1





    @SamYonnou with a map defined like this Map<ArrayList<String>, String>, get with a LinkedList<String> instance would still work and retrieve the correct value as in the equals method the instanceof is done w.r.t to List and both ArrayList and LinkedList instances would satisfy that as I mentioned in my answer. And for the actual question many people have already pointed out that it is unnecessary and provided sample code to do it either way. I also explained that with a well defined equals method why it won't be necessary. :)

    – Amardeep Bhowmick
    Apr 22 at 15:32















17














It is designed that way, since during the get operation only the equals and hashCode is used to determine the object to be returned. The implementation of the get method does not check for the type of the Object used as the key.



In your example you are trying to get the value by passing a long like myHashMap.get(1L);, firstly the hash code of the object Long having the value 1L will be used to determine the bucket from which to look for. Next the equals method of the key is used to find out the exact entry of the map from which to return the value. And in a well-defined equals method there is always a check for the type:



public boolean equals(Object obj) 
if (obj instanceof Long) //here type is checked
return value == ((Long)obj).longValue();

return false;



So if the types are not equal, the equals method returns false and hence get also will return null.



In some cases such as when using List as a key, it may happen that you put an item in the map using an instance of say an ArrayList but you can successfully retrieve the same value with an instance of an LinkedList. As both implement the List interface.



Map<List<String>, String> myHashMap = new HashMap<>();
List<String> arrayList = new ArrayList<>();
List<String> linkedList = new LinkedList<>();
myHashMap.put(arrayList, "foo");
System.out.println(myHashMap.get(linkedList));


The above code will output in the console foo.



Here although the implementations are different but if you examine the equals method of ArrayList, it is only checking if the type is a List:



public boolean equals(Object o) 
if (o == this)
return true;


if (!(o instanceof List)) //checking type of super interface
return false;

...



The same is true for LinkedList.






share|improve this answer




















  • 2





    This is a good example of how an answer should be written in StackOverflow - well formulated, informative, with to-the-point code examples. Well done!

    – Rann Lifshitz
    Apr 22 at 8:04






  • 1





    This answer is failing to address the "compilation error" aspect of the question and missing the implicit question of why Map.get is declared to accept Object instead of the K parameterized type.

    – Miles
    Apr 22 at 9:53






  • 1





    @Miles that question has already been answered here and here.

    – Moira
    Apr 22 at 14:11












  • As per the first link @Moira posted the List example should have the map type be something like Map<ArrayList<String>, String> instead. If the key type is List<String> then V get(K key) will still work and compile fine with both ArrayList and LinkedList. Also this answer does not attempt to answer OP's actual question "Is there a way I can restrict the datatype which I pass as an argument in the get method?"

    – SamYonnou
    Apr 22 at 15:03







  • 1





    @SamYonnou with a map defined like this Map<ArrayList<String>, String>, get with a LinkedList<String> instance would still work and retrieve the correct value as in the equals method the instanceof is done w.r.t to List and both ArrayList and LinkedList instances would satisfy that as I mentioned in my answer. And for the actual question many people have already pointed out that it is unnecessary and provided sample code to do it either way. I also explained that with a well defined equals method why it won't be necessary. :)

    – Amardeep Bhowmick
    Apr 22 at 15:32













17












17








17







It is designed that way, since during the get operation only the equals and hashCode is used to determine the object to be returned. The implementation of the get method does not check for the type of the Object used as the key.



In your example you are trying to get the value by passing a long like myHashMap.get(1L);, firstly the hash code of the object Long having the value 1L will be used to determine the bucket from which to look for. Next the equals method of the key is used to find out the exact entry of the map from which to return the value. And in a well-defined equals method there is always a check for the type:



public boolean equals(Object obj) 
if (obj instanceof Long) //here type is checked
return value == ((Long)obj).longValue();

return false;



So if the types are not equal, the equals method returns false and hence get also will return null.



In some cases such as when using List as a key, it may happen that you put an item in the map using an instance of say an ArrayList but you can successfully retrieve the same value with an instance of an LinkedList. As both implement the List interface.



Map<List<String>, String> myHashMap = new HashMap<>();
List<String> arrayList = new ArrayList<>();
List<String> linkedList = new LinkedList<>();
myHashMap.put(arrayList, "foo");
System.out.println(myHashMap.get(linkedList));


The above code will output in the console foo.



Here although the implementations are different but if you examine the equals method of ArrayList, it is only checking if the type is a List:



public boolean equals(Object o) 
if (o == this)
return true;


if (!(o instanceof List)) //checking type of super interface
return false;

...



The same is true for LinkedList.






share|improve this answer















It is designed that way, since during the get operation only the equals and hashCode is used to determine the object to be returned. The implementation of the get method does not check for the type of the Object used as the key.



In your example you are trying to get the value by passing a long like myHashMap.get(1L);, firstly the hash code of the object Long having the value 1L will be used to determine the bucket from which to look for. Next the equals method of the key is used to find out the exact entry of the map from which to return the value. And in a well-defined equals method there is always a check for the type:



public boolean equals(Object obj) 
if (obj instanceof Long) //here type is checked
return value == ((Long)obj).longValue();

return false;



So if the types are not equal, the equals method returns false and hence get also will return null.



In some cases such as when using List as a key, it may happen that you put an item in the map using an instance of say an ArrayList but you can successfully retrieve the same value with an instance of an LinkedList. As both implement the List interface.



Map<List<String>, String> myHashMap = new HashMap<>();
List<String> arrayList = new ArrayList<>();
List<String> linkedList = new LinkedList<>();
myHashMap.put(arrayList, "foo");
System.out.println(myHashMap.get(linkedList));


The above code will output in the console foo.



Here although the implementations are different but if you examine the equals method of ArrayList, it is only checking if the type is a List:



public boolean equals(Object o) 
if (o == this)
return true;


if (!(o instanceof List)) //checking type of super interface
return false;

...



The same is true for LinkedList.







share|improve this answer














share|improve this answer



share|improve this answer








edited Apr 22 at 8:00

























answered Apr 22 at 7:38









Amardeep BhowmickAmardeep Bhowmick

6,46121231




6,46121231







  • 2





    This is a good example of how an answer should be written in StackOverflow - well formulated, informative, with to-the-point code examples. Well done!

    – Rann Lifshitz
    Apr 22 at 8:04






  • 1





    This answer is failing to address the "compilation error" aspect of the question and missing the implicit question of why Map.get is declared to accept Object instead of the K parameterized type.

    – Miles
    Apr 22 at 9:53






  • 1





    @Miles that question has already been answered here and here.

    – Moira
    Apr 22 at 14:11












  • As per the first link @Moira posted the List example should have the map type be something like Map<ArrayList<String>, String> instead. If the key type is List<String> then V get(K key) will still work and compile fine with both ArrayList and LinkedList. Also this answer does not attempt to answer OP's actual question "Is there a way I can restrict the datatype which I pass as an argument in the get method?"

    – SamYonnou
    Apr 22 at 15:03







  • 1





    @SamYonnou with a map defined like this Map<ArrayList<String>, String>, get with a LinkedList<String> instance would still work and retrieve the correct value as in the equals method the instanceof is done w.r.t to List and both ArrayList and LinkedList instances would satisfy that as I mentioned in my answer. And for the actual question many people have already pointed out that it is unnecessary and provided sample code to do it either way. I also explained that with a well defined equals method why it won't be necessary. :)

    – Amardeep Bhowmick
    Apr 22 at 15:32












  • 2





    This is a good example of how an answer should be written in StackOverflow - well formulated, informative, with to-the-point code examples. Well done!

    – Rann Lifshitz
    Apr 22 at 8:04






  • 1





    This answer is failing to address the "compilation error" aspect of the question and missing the implicit question of why Map.get is declared to accept Object instead of the K parameterized type.

    – Miles
    Apr 22 at 9:53






  • 1





    @Miles that question has already been answered here and here.

    – Moira
    Apr 22 at 14:11












  • As per the first link @Moira posted the List example should have the map type be something like Map<ArrayList<String>, String> instead. If the key type is List<String> then V get(K key) will still work and compile fine with both ArrayList and LinkedList. Also this answer does not attempt to answer OP's actual question "Is there a way I can restrict the datatype which I pass as an argument in the get method?"

    – SamYonnou
    Apr 22 at 15:03







  • 1





    @SamYonnou with a map defined like this Map<ArrayList<String>, String>, get with a LinkedList<String> instance would still work and retrieve the correct value as in the equals method the instanceof is done w.r.t to List and both ArrayList and LinkedList instances would satisfy that as I mentioned in my answer. And for the actual question many people have already pointed out that it is unnecessary and provided sample code to do it either way. I also explained that with a well defined equals method why it won't be necessary. :)

    – Amardeep Bhowmick
    Apr 22 at 15:32







2




2





This is a good example of how an answer should be written in StackOverflow - well formulated, informative, with to-the-point code examples. Well done!

– Rann Lifshitz
Apr 22 at 8:04





This is a good example of how an answer should be written in StackOverflow - well formulated, informative, with to-the-point code examples. Well done!

– Rann Lifshitz
Apr 22 at 8:04




1




1





This answer is failing to address the "compilation error" aspect of the question and missing the implicit question of why Map.get is declared to accept Object instead of the K parameterized type.

– Miles
Apr 22 at 9:53





This answer is failing to address the "compilation error" aspect of the question and missing the implicit question of why Map.get is declared to accept Object instead of the K parameterized type.

– Miles
Apr 22 at 9:53




1




1





@Miles that question has already been answered here and here.

– Moira
Apr 22 at 14:11






@Miles that question has already been answered here and here.

– Moira
Apr 22 at 14:11














As per the first link @Moira posted the List example should have the map type be something like Map<ArrayList<String>, String> instead. If the key type is List<String> then V get(K key) will still work and compile fine with both ArrayList and LinkedList. Also this answer does not attempt to answer OP's actual question "Is there a way I can restrict the datatype which I pass as an argument in the get method?"

– SamYonnou
Apr 22 at 15:03






As per the first link @Moira posted the List example should have the map type be something like Map<ArrayList<String>, String> instead. If the key type is List<String> then V get(K key) will still work and compile fine with both ArrayList and LinkedList. Also this answer does not attempt to answer OP's actual question "Is there a way I can restrict the datatype which I pass as an argument in the get method?"

– SamYonnou
Apr 22 at 15:03





1




1





@SamYonnou with a map defined like this Map<ArrayList<String>, String>, get with a LinkedList<String> instance would still work and retrieve the correct value as in the equals method the instanceof is done w.r.t to List and both ArrayList and LinkedList instances would satisfy that as I mentioned in my answer. And for the actual question many people have already pointed out that it is unnecessary and provided sample code to do it either way. I also explained that with a well defined equals method why it won't be necessary. :)

– Amardeep Bhowmick
Apr 22 at 15:32





@SamYonnou with a map defined like this Map<ArrayList<String>, String>, get with a LinkedList<String> instance would still work and retrieve the correct value as in the equals method the instanceof is done w.r.t to List and both ArrayList and LinkedList instances would satisfy that as I mentioned in my answer. And for the actual question many people have already pointed out that it is unnecessary and provided sample code to do it either way. I also explained that with a well defined equals method why it won't be necessary. :)

– Amardeep Bhowmick
Apr 22 at 15:32













4














I think if it is very important in a project that we control type in HashMap, we could extend HashMap and force using this class instead of HashMap like the below code.



We have all HashMap capabilities, and we should just use the getValue method instead of the get method.



import java.util.HashMap;

public class MyHashMap<K,V> extends HashMap<K,V>

public V getValue(K key)
return super.get(key);




Test class:



 public class Test 
public static void main(String[] args)
MyHashMap<String,Integer> map = new MyHashMap();







share|improve this answer




















  • 2





    A similar answer was posted maybe an hour ago and was then deleted by its poster...........

    – Rann Lifshitz
    Apr 22 at 8:02















4














I think if it is very important in a project that we control type in HashMap, we could extend HashMap and force using this class instead of HashMap like the below code.



We have all HashMap capabilities, and we should just use the getValue method instead of the get method.



import java.util.HashMap;

public class MyHashMap<K,V> extends HashMap<K,V>

public V getValue(K key)
return super.get(key);




Test class:



 public class Test 
public static void main(String[] args)
MyHashMap<String,Integer> map = new MyHashMap();







share|improve this answer




















  • 2





    A similar answer was posted maybe an hour ago and was then deleted by its poster...........

    – Rann Lifshitz
    Apr 22 at 8:02













4












4








4







I think if it is very important in a project that we control type in HashMap, we could extend HashMap and force using this class instead of HashMap like the below code.



We have all HashMap capabilities, and we should just use the getValue method instead of the get method.



import java.util.HashMap;

public class MyHashMap<K,V> extends HashMap<K,V>

public V getValue(K key)
return super.get(key);




Test class:



 public class Test 
public static void main(String[] args)
MyHashMap<String,Integer> map = new MyHashMap();







share|improve this answer















I think if it is very important in a project that we control type in HashMap, we could extend HashMap and force using this class instead of HashMap like the below code.



We have all HashMap capabilities, and we should just use the getValue method instead of the get method.



import java.util.HashMap;

public class MyHashMap<K,V> extends HashMap<K,V>

public V getValue(K key)
return super.get(key);




Test class:



 public class Test 
public static void main(String[] args)
MyHashMap<String,Integer> map = new MyHashMap();








share|improve this answer














share|improve this answer



share|improve this answer








edited Apr 22 at 13:52









Peter Mortensen

14k1987114




14k1987114










answered Apr 22 at 8:01









hamid rostamihamid rostami

1117




1117







  • 2





    A similar answer was posted maybe an hour ago and was then deleted by its poster...........

    – Rann Lifshitz
    Apr 22 at 8:02












  • 2





    A similar answer was posted maybe an hour ago and was then deleted by its poster...........

    – Rann Lifshitz
    Apr 22 at 8:02







2




2





A similar answer was posted maybe an hour ago and was then deleted by its poster...........

– Rann Lifshitz
Apr 22 at 8:02





A similar answer was posted maybe an hour ago and was then deleted by its poster...........

– Rann Lifshitz
Apr 22 at 8:02



Popular posts from this blog

Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020