Java HashMap get method null pointer exception
If c is not contained in myMap, it will return null, which can’t be unboxed as a boolean. Try : Boolean b = myMap.get(c); if(b != null && b){ …
If c is not contained in myMap, it will return null, which can’t be unboxed as a boolean. Try : Boolean b = myMap.get(c); if(b != null && b){ …
Yes, it can be a constant. You should declare your HashMap instance as follows: class <class name> { private static final HashMap<Integer, String> tensNumberConversion = new HashMap<>(); static { tensNumberConversion.put(2, “twenty”); tensNumberConversion.put(3, “thirty”); tensNumberConversion.put(4, “forty”); tensNumberConversion.put(5, “fifty”); tensNumberConversion.put(6, “sixty”); tensNumberConversion.put(7, “seventy”); tensNumberConversion.put(8, “eighty”); tensNumberConversion.put(9, “ninety”); } } However, this is only a constant reference. While … Read more
It’s fine with Integer, but not okay with int – Java generics only work with reference types, basically 🙁 Try this – although be aware it will box everything: HashMap<String,Integer> userName2ind = new HashMap<String,Integer>(); for (int i=0; i<=players.length; i++) { userName2ind.put(orderedUserNames[i],i+1); }
You link is for the HashMap in Java 6. It was rewritten in Java 8. Prior to this rewrite an infinite loop on get(Object) was possible if there were two writing threads. I am not aware of a way the infinite loop on get can occur with a single writer. Specifically, the infinite loop occurs … Read more
The short answer To find out how large an object is, I would use a profiler. In YourKit, for example, you can search for the object and then get it to calculate its deep size. This will give a you a fair idea of how much memory would be used if the object were stand … Read more
To answer the question in the title – as mentioned by others, containsValue is O(n), because without the key it doesn’t know where it is and the algorithm has to go over all the values stored in the map. To answer the question in the body of your question – on how to solve it … Read more
A Hash is a sparse array that uses arbitrary strings/objects (depending on the implementation, this varies across programming languages) rather than plain integers as keys. In Javascript, any Object is technically a hash (also referred to as a Dictionary, Associative-Array, etc). Examples: var myObj = {}; // Same as = new Object(); myObj[‘foo’] = ‘bar’; … Read more
The put method in HashMap is defined like this: Object put(Object key, Object value) key is the first parameter, so in your put, “one” is the key. You can’t easily look up by value in a HashMap, if you really want to do that, it would be a linear search done by calling entrySet(), like … Read more